Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow multiple JWT with different issuers in asp.net core 2.0

Is there a way to handle JWTs from multiple issuers in single asp.net core 2.0 application?

Here how I'm currently checking tokens:

public void ConfigureServices(IServiceCollection services)
{
    TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
    {
        // ...

        ValidateIssuer = true,
        ValidIssuer = options.Issuer, // <-- could this be a list of issuers?

        // ...
    };

    services.AddAuthentication()
        .AddJwtBearer(jwtOptions =>
        {
            jwtOptions.TokenValidationParameters = tokenValidationParameters;
        });

    services.AddAuthorization(authOptions =>
        {
            authOptions.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build();
        });
}

public void Configure(IApplicationBuilder app)
{   
    // ...
    app.UseAuthentication();
}

The reason why I want to handle multiple issuers is because I need to handle different user types with different kind of permissions. To allow specific users only on some services in a microservice architecture environment I would like to issue tokens for each user type with a different issuer.

like image 264
Mathias Avatar asked Oct 02 '17 05:10

Mathias


1 Answers

The simple answer would be to set the ValidIssuers property of the TokenValidationParameters instance instead of the ValidIssuer property. The ValidIssuers property takes an IEnumerable, so you can fill a list of issuer names and assign it to that property (or just inline the list).

var issuers = new List<string>()
    {
        "issuerA",
        "issuerB"
    };
// ...
TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
{
    // ...

    ValidateIssuer = true,
    ValidIssuers = issuers

    // ...
};

Caveat: This assumes that each issuer shares the same secret (or list of secrets, if you use the corresponding IssuerSigningKeys property instead of the IssuerSigningKey property).

like image 65
Jarod C Avatar answered Oct 20 '22 12:10

Jarod C