aph5
aph5

Reputation: 791

asp.net core identity - 2 types of jwt tokens

I just wonder, is it possible to configure JWT tokens for 2 different audiences ? First would have a token expiry date set and the second one not.

I have the following code for JWT configuration, but it works for a single audience only.

private void ConfigureSecurity(IServiceCollection services)
    {
        services.AddAuthentication()
            .AddCookie(cfg => cfg.SlidingExpiration = true)
            .AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata = false;
                cfg.SaveToken = true;

                cfg.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    RequireExpirationTime = false,
                    ValidIssuer = Configuration["Tokens:Issuer"],
                    ValidAudience = Configuration["Tokens:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])),
                };
            });

        services.AddAuthorization();
    }

Upvotes: 0

Views: 303

Answers (1)

Neville Nazerane
Neville Nazerane

Reputation: 7019

There are a couple of things you can try. First of the AddJwtBearer function accepts a scheme name too. You can try adding two JwtBearers with different scheme names. Not entirely sure if it will allow multiple jwts though

Another way is make to try configuring your own JwtEventBearer and set it to cfg.Events.

If all else fails, you can always manually create and validate the jwt. You will first need to make the two token validation parameters objects. You can create your token like this:

        var handler = new JwtSecurityTokenHandler();

        var jwt = handler.CreateJwtSecurityToken(new SecurityTokenDescriptor
        {
            Audience = myAudience, 
            Expires = DateTime.UtcNow.Add(Expiary),
            Subject = myPrincipal,
            SigningCredentials = Signing
        });

        return handler.WriteToken(jwt);

For validation, you can first check the audience:

        var _token = handle.ReadJwtToken(token);
        if (_token.Audiences == ...)

Once you find out what the audience is and which token validation parameters to use, you can validate with this:

        SecurityToken sToken = handle.CreateJwtSecurityToken();
        var myPrincipal = handle.ValidateToken(token, TokenValidationParameters, out sToken);

Upvotes: 1

Related Questions