Untitled

mail@pastecode.io avatar
unknown
csharp
2 months ago
3.7 kB
1
Indexable
Never
public static void ConfigureServices(IServiceCollection services, OpenIdConnectSettings settings)
{

    services.AddHttpContextAccessor();

    using var handler = new HttpClientHandler();
    if (settings.DisableCertificateValidation)
    {
        handler.ClientCertificateOptions = ClientCertificateOption.Manual;
        handler.ServerCertificateCustomValidationCallback =
            (_, _, _, _) =>
            {
                return true;
            };
    }

    using var httpClient = new HttpClient(handler);
    var config = OpenIdConnectConfiguration.Create(httpClient.GetStringAsync(settings.MetadataAddress).Result);
    var certificates = httpClient.GetStringAsync(config.JwksUri).Result;
    config.JsonWebKeySet = new JsonWebKeySet(certificates);

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = AuthenticationDefaults.AuthenticationScheme;
    }).AddJwtBearer(AuthenticationDefaults.AuthenticationScheme, options =>
    {
        options.Audience = settings.ClientId;
        options.Authority = config.Issuer;
        options.RequireHttpsMetadata = settings.RequireHttps;
        options.MetadataAddress = settings.MetadataAddress;

        if (settings.DisableCertificateValidation)
        {
            options.BackchannelHttpHandler = new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
            };
        }

        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateAudience = settings.ValidateAudience,
            ValidateIssuer = settings.ValidateIssuer,
            ValidIssuer = config.Issuer,
            ValidateLifetime = settings.ValidateLifetime,
            ValidateIssuerSigningKey = settings.ValidateIssuerSigningKey,
            IssuerSigningKeys = config.JsonWebKeySet.GetSigningKeys(),
            ClockSkew = TimeSpan.FromSeconds(settings.ClockSkewSeconds)
        };
        options.Events = new JwtBearerEvents()
        {
            OnAuthenticationFailed = context =>
            {
                context.Response.StatusCode = 401;
                context.Response.Headers.Add("WWW-Authenticate", AuthenticationDefaults.AuthenticationScheme);
                return Task.CompletedTask;
            },
            OnMessageReceived = context =>
            {
                var cookie = context.Request.Cookies[OpenIdConstants.AuthCookieName];
                if (cookie != null && !context.Request.Headers.ContainsKey(OpenIdConstants.AuthHeaderName))
                    context.Request.Headers.Add(OpenIdConstants.AuthHeaderName, new[] { cookie });
                return Task.CompletedTask;
            },
            OnTokenValidated = context =>
            {
                var userName = context.Principal.Claims.FirstOrDefault(t => t.Type == settings.NeonUserIdentityClaim).Value;

                var headers = context.HttpContext.Request.Headers;
                if (headers.ContainsKey(NeonUserIdentity.NeonUserIdentityHeader))
                    headers[NeonUserIdentity.NeonUserIdentityHeader] = new string[] { userName };
                else
                    headers.Add(NeonUserIdentity.NeonUserIdentityHeader, new string[] { userName });

                context.Response.Cookies.Append(OpenIdConstants.AuthCookieName, context.Request.Headers[OpenIdConstants.AuthHeaderName], new CookieOptions() { HttpOnly = true });

                return Task.CompletedTask;
            }
        };
    });
}

public static void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<OpenIdMiddleware>();
    app.UseAuthentication();
}
Leave a Comment