Basic authentication might be a bad idea for most things, but still very useful for some very specific applications.
First, we’ll add the idunno package to
dotnet add package idunno.Authentication.Basic
We register a new scheme called BasicAuthentication
to handle our verification, using credentials stored in our configuration (preferably loaded from KeyVault).
services.AddAuthentication(options => { ... }) .AddCookie("Cookies", options => { ... } .AddBasic("BasicAuthentication", options => { options.Realm = "Basic Authentication"; options.Events = new BasicAuthenticationEvents { OnValidateCredentials = context => { if (context.Username == Configuration["Metrics:Username"] && context.Password == Configuration["Metrics:Password"]) { var claims = new[] { new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer) }; context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name)); context.Success(); } return Task.CompletedTask; } }; })
Next, we’ll configure our authorization policy to use the BasicAuthentication scheme
services.AddAuthorization(options => { ... options.AddPolicy("ViewMetrics", new AuthorizationPolicyBuilder("BasicAuthentication").RequireAuthenticatedUser().Build()); ... });
And finally, we add the authorization policy on our Metrics route, or any route we need.
app.UseEndpoints(endpoints => { ... endpoints.MapMetrics().RequireAuthorization("ViewMetrics"); ... });
Quick Links
Legal Stuff