7

I have created custom middleware class which validates the JWT token. I am calling this method before app.AddMvc() in configure method.

What should I add to Configuration services to authenticate my web API using JWT? I have added [Authorize] in my Controller class.

Do I need to call my middleware class which validates the JWT token first in Configure method? or I should call App.UseAuthentication() I am using the following order:

 app.UseAuthentication();
 app.MessageHandlerMiddleware();
 app.UseMvc();

I am new to .net web API implementation.

4
  • 2
    What's the reason for creating a "custom middleware class" for the JWT validation? Is there a specific reason you can't use the built-in validation process? Commented Aug 21, 2018 at 7:46
  • To be frank, I am not sure how to validate it using built in validation process!! Due to which I have created y own stuff for authentication Commented Aug 21, 2018 at 9:25
  • 1
    Have a read through Securing ASP.NET Core 2.0 Applications with JWTs and see if it helps. Commented Aug 21, 2018 at 11:15
  • Thanks Kirik Larkin. Let me check it Commented Aug 21, 2018 at 12:07

1 Answer 1

4

From one of my answers you can see how we pass JWT token and how the code looks for classic .NET (non-core) ASP.NET WebAPI 2.

There are not many differences, the code for ASP.NET Core looks similar.

The key aspect is - when you add JWT config in Startup the app handles validation automatically.

services
    .AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
        x.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
            ValidAudience = _configuration.GetValidAudience(),
            ValidIssuer = _configuration.GetValidIssuer()
        };
    });

(use the above link to see the implementation of GetSymmetricSecurityKey, GetValidAudience, GetValidIssuer ext. methods)

Also very important part:

services.AddAuthorization(auth =>
{
    auth
    .AddPolicy(
        _configuration.GetDefaultPolicy(),
        new AuthorizationPolicyBuilder()
            .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
            .RequireAuthenticatedUser().Build()
    );
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.