-
Notifications
You must be signed in to change notification settings - Fork 250
/
Copy pathBasicAuthExtensions.cs
41 lines (33 loc) · 1.88 KB
/
BasicAuthExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System.Security.Claims;
using idunno.Authentication.Basic;
using Microsoft.AspNetCore.Authentication;
namespace Steeltoe.Samples.ActuatorWeb;
internal static class BasicAuthExtensions
{
public static void ConfigureActuatorAuth(this IServiceCollection services)
{
AuthenticationBuilder builder = services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme);
builder.AddBasic(BasicAuthenticationDefaults.AuthenticationScheme, options =>
{
// This line allows basic auth to work over HTTP (which is insecure), because docker containers don't trust the ASP.NET dev certificate.
options.AllowInsecureProtocol = true;
options.ForwardDefaultSelector = httpContext =>
httpContext.Request.Path.StartsWithSegments("/actuator") ? BasicAuthenticationDefaults.AuthenticationScheme : null;
options.ForwardChallenge = BasicAuthenticationDefaults.AuthenticationScheme;
options.Events = new BasicAuthenticationEvents
{
OnValidateCredentials = validateCredentialsContext =>
{
// This sample hard-codes the username and password for simplicity. In a real-world scenario, they are typically fetched from an external system.
if (validateCredentialsContext.Username == "actuatorUser" && validateCredentialsContext.Password == "actuatorPassword")
{
validateCredentialsContext.Principal = new ClaimsPrincipal(new ClaimsIdentity([new Claim("scope", "actuator.read")]));
validateCredentialsContext.Success();
}
return Task.CompletedTask;
}
};
});
services.AddAuthorizationBuilder().AddPolicy("actuator.read", policy => policy.RequireClaim("scope", "actuator.read"));
}
}