Skip to content

Instantly share code, notes, and snippets.

@zola-25
Created April 30, 2023 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zola-25/c1137903a6f7213422859e473faf1179 to your computer and use it in GitHub Desktop.
Save zola-25/c1137903a6f7213422859e473faf1179 to your computer and use it in GitHub Desktop.
HTTP Basic Access Authentication - Raw Implementation in .NET
using System.Text;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
var app = WebApplication.Create(args);
string validUsername = "user1";
string validPassword = "password123";
app.MapGet("/", (HttpContext httpContext) =>
{
if (!HasAuthorizationHeader(httpContext))
{
if (!httpContext.Request.Headers[HeaderNames.Authorization].Any())
{
httpContext.Response.Headers.Add(HeaderNames.WWWAuthenticate,
new StringValues(new[] { "Basic", "realm=\"User Visible Realm\", charset=\"UTF-8\"" }));
return Results.Unauthorized();
}
}
var authorizationHeaders = httpContext.Request.Headers[HeaderNames.Authorization];
if (authorizationHeaders.Count != 1)
{
return Results.Content("Expecting one Authorization header", statusCode: StatusCodes.Status401Unauthorized);
}
var authorizationHeader = authorizationHeaders[0]!;
if (!authorizationHeader.StartsWith("Basic "))
{
return Results.Content("'Basic ' authorization scheme expected", statusCode: StatusCodes.Status401Unauthorized);
}
var encodedCredentials = authorizationHeader.Replace("Basic ", String.Empty);
var decodedBytes = Convert.FromBase64String(encodedCredentials);
var credentials = Encoding.UTF8.GetString(decodedBytes).Split(":");
var username = credentials[0];
var password = credentials[1];
if (username == validUsername && password == validPassword)
{
return Results.Text("User Authorized! <br/> <br/> <b>The Permitted content authorized for user</b>", "text/html");
}
return Results.Content("Invalid credentials", statusCode: StatusCodes.Status401Unauthorized);
});
app.UseHttpsRedirection();
app.Run();
bool HasAuthorizationHeader(HttpContext httpContext)
{
return httpContext.Request.Headers.ContainsKey(HeaderNames.Authorization);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment