BasicAuthenticationMiddleware Class
Definition
- Namespace
- Cuemon.AspNetCore.Authentication.Basic
- Assemblies
- Cuemon.AspNetCore.Authentication.dll
Provides a HTTP Basic Authentication middleware implementation for ASP.NET Core.
public class BasicAuthenticationMiddleware : ConfigurableMiddleware<BasicAuthenticationOptions>, IConfigurable<BasicAuthenticationOptions>
- Inheritance
-
BasicAuthenticationMiddleware
- Implements
- Inherited Members
Examples
The following example demonstrates how to construct BasicAuthenticationMiddleware with inline option setup and invoke it against a DefaultHttpContext carrying a Basic Authorization header.
// Program.cs
using System;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Cuemon.AspNetCore.Authentication.Basic;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
var middleware = new BasicAuthenticationMiddleware(_ => Task.CompletedTask, options =>
{
options.Realm = "docs-example";
options.RequireSecureConnection = false;
options.Authenticator = (username, password) =>
{
if (username == "Agent" && password == "Test")
{
return new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, username) }, BasicAuthorizationHeader.Scheme));
}
return null;
};
});
var context = new DefaultHttpContext();
var credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes("Agent:Test"));
context.Request.Headers[HeaderNames.Authorization] = $"{BasicAuthorizationHeader.Scheme} {credentials}";
await middleware.InvokeAsync(context);
Console.WriteLine($"Realm: {middleware.Options.Realm}");
Console.WriteLine($"Authenticated: {context.User.Identity?.IsAuthenticated}");
Console.WriteLine($"User: {context.User.Identity?.Name}");
Constructors
| Name | Description |
|---|---|
| BasicAuthenticationMiddleware(RequestDelegate, IOptions<BasicAuthenticationOptions>) | Initializes a new instance of the BasicAuthenticationMiddleware class. |
| BasicAuthenticationMiddleware(RequestDelegate, Action<BasicAuthenticationOptions>) | Initializes a new instance of the BasicAuthenticationMiddleware class. |
Methods
| Name | Description |
|---|---|
| InvokeAsync(HttpContext) | Executes the BasicAuthenticationMiddleware. |