Home > Enterprise >  Multiple JWT Tokens and Multiple Auth Handlers
Multiple JWT Tokens and Multiple Auth Handlers

Time:09-29

I currently have Auth in place for my API application using a JWT token with Identity User, Which works great, I am now trying to chain on another JWT Token which users keycloak and I want to setup A custom auth Handler just for that token type, is that possible? My Code looks as follows:

services.AddAuthentication()
        .AddJwtBearer("KeyCloak", opt =>
        {
             opt.Authority = "site.co.za/auth/realms/Development";
             opt.Audience = "dev";
             opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidAudiences = new string[] { "dev" },
                    NameClaimType = "preferred_username",
                    RoleClaimType = "role"
                };
                opt.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = c =>
                    {
                        c.NoResult();

                        c.Response.StatusCode = 500;
                        c.Response.ContentType = "text/plain";
                        return c.Response.WriteAsync(c.Exception.ToString());
                    }
                };
                opt.RequireHttpsMetadata = false;
                opt.SaveToken = true;
                opt.Validate();


            })
            .AddJwtBearer("Internal", opt =>
            {
                opt.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Constants.AuthTokenKey))
                };
            });

services.AddAuthorization(options =>
{
       options.DefaultPolicy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .AddAuthenticationSchemes("KeyCloak", "Internal").Build();
 });

I need to add a custom Auth HandleAuthenticateAsync just for keycloak and use the normal out of the box HandleAuthenticateAsync for internal. Is this possible to do?

CodePudding user response:

You can do this:

this will select the jwt token validation based on API path.

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "Custom";
})
.AddPolicyScheme("Custom", "Custom", options =>
{
    options.ForwardDefaultSelector = context =>
    {
        bool isKeyCloakAuthRequired = context.Request.Path.StartsWithSegments("/apithatneedskeycloakauth");
        if (isKeyCloakAuthRequired)
        {
            return "Keycloak";
        }
        else
        {
            return "Internal";
        }
    };

})
.AddJwtBearer("Keycloak", options =>
{
    // your code for keycloak validation parameters.
})
.AddJwtBearer("Internal", options =>
{
    // your code for token validation parameters.
})

Hope it helps.

  • Related