Do I need to validate JWT tokens in asp.net core 2 REST API?

1.1k Views Asked by At

I have the following code in my asp.net core REST API configuration:

services
    .AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
    .AddJwtBearer(options =>
        {
            options.Authority = "https://login.microsoftonline.com/XXXTenantIDXXX";
            options.Audience = "XXXX clientId XXXX";
        });

services.AddMvc(o =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        o.Filters.Add(new AuthorizeFilter(policy));

It authenticates requests. It is working fine.

I am concerned and worried about jwt token forgery or jwt tokens that come from other AAD applications in the tenant.

I expect above code provides all the information to the asp.net core authentication to verify the jwt is valid and its audience is the right AAD application.

I wanted to confirm my expectation here and ask if I need to have additional logic (code) to verify the JWT token?

1

There are 1 best solutions below

0
On BEST ANSWER

Yes, Asp.Net Core Middleware validates JWT Token. Make sure you are configuring JWT Bearer Options and token validation parameters in order for Asp.Net Core Middleware to validate it.

For example:

      services.AddAuthentication(auth =>
        {
            auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {               
            options.ClaimsIssuer = jwtAuthSettings.ValidIssuer;//Your issuer
            options.IncludeErrorDetails = true;
            options.RequireHttpsMetadata = true;
            options.SaveToken = true;
            options.Validate(JwtBearerDefaults.AuthenticationScheme);
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ClockSkew = TimeSpan.FromMinutes(30),
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = jwtAuthSettings.ValidIssuer, //Your issuer
                ValidAudience = jwtAuthSettings.ValidAudience,//Your Audience
                IssuerSigningKey = jwtAuthSettings.SymmetricSecurityKey, //Your Key
                NameClaimType = ClaimTypes.NameIdentifier,
                RequireSignedTokens = true,
                RequireExpirationTime = true

            };
        });