C# / .NETDevOpsMisc
C# / .NET
Basic Authentication in C# / .NET
Alexandru Puiu
Alexandru Puiu
December 21, 2022
1 min

Basic authentication might be a bad idea for most things, but still very useful for some very specific applications.

Using basic authentication to protect the Prometheus /metric endpoint

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).

  • This implementation is very simple, which is what this use-case requires, but is subject to brute forcing, so that should be consdidered.
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");
    ...
});

Tags

utilssecurity
Alexandru Puiu

Alexandru Puiu

Engineer / Security Architect

Systems Engineering advocate, Software Engineer, Security Architect / Researcher, SQL/NoSQL DBA, and Certified Scrum Master with a passion for Distributed Systems, AI and IoT..

Expertise

.NET
RavenDB
Kubernetes

Social Media

githubtwitterwebsite

Related Posts

RavenDB Integration Testing
Using RavenDB in Integration Testing
December 24, 2022
2 min

Subscribe To My Newsletter

I'll only send worthwhile content I think you'll want, less than once a month, and promise to never spam or sell your information!
© 2023, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media