0

I am working on a project in ASP.NET Core which I am using JWT tokens to authenticate users.

I have configured the JWTBearerDefaults in my Startup.cs file as following:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
 .AddJwtBearer(options =>
 {
     options.TokenValidationParameters = new TokenValidationParameters
     {
         ValidateIssuer = true,
         ValidateAudience = true,
         ValidateLifetime = true,
         ValidateIssuerSigningKey = true,
         ValidIssuer = "some.issuer",
         ValidAudience = "some.issuer",
         ClockSkew = TimeSpan.Zero,
         IssuerSigningKey = new SymmetricSecurityKey(
             Encoding.UTF8.GetBytes(Configuration["SecurityKey"])),
     };

     options.EventsType = typeof(CustomJwtBearerEvents);
 });

My requirement is, whenever an API call is received, i should be able to get the token and do some validations. For each method in my API Controller, I can check for the token and perform the validations, but I want that validation to be called from a single place. So for that purposes, on the top code I added options.EventsType line.

But the problem is, as soon as I added this line, all the API calls fail because the server throws a 500 internal server error, and also a CORS policy error. But everything works fine without this line.

This is the error that I get in my client browser:

  • Failed to load resource: the server responded with a status of 500 (Internal Server Error)
  • Access to XMLHttpRequest at 'http://localhost:58402/api/User/GetAllDurations' from origin 'http://localhost:56040' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Any ideas, why this is happening? Is there any other mechanism to achieve this goal?

4
  • Did you try instantiating JwtBearerEvents and setting your validation there instead of using a custom events type? Commented Jan 10, 2019 at 7:22
  • @juunas I am still a beginner in using JWT tokens. I would be glad if you could tell me how it can be done in Startup.cs Commented Jan 10, 2019 at 7:32
  • I think it's something like options.Events = new JwtBearerEvents { }. Then you can use IntelliSense to figure out what event properties are available there :) Commented Jan 10, 2019 at 7:35
  • @juunas Thank you very much. This actually helped me. Commented Jan 10, 2019 at 8:10

2 Answers 2

2

You can do that by implementing ISecurityTokenValidator interface.

public class MySecurityTokenValidator : ISecurityTokenValidator
{
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
           //// Perform your custom validation here.
        }
}

In Startup, you will have to configure this new logic as below:

        var bearerOptions = new JwtBearerOptions();
        bearerOptions.SecurityTokenValidators.Add(new MySecurityTokenValidator(app.ApplicationServices, Encoding.UTF8.GetBytes("SecurityKey1234567890")));
        app.UseJwtBearerAuthentication(bearerOptions);

You can refer this blog for custom implementation.

Sign up to request clarification or add additional context in comments.

Comments

0

Have you registered the CustomJwtBearerEvents class in the Dependency Injection container? You could do so like:

services.AddTransient<CustomJwtBearerEvents>();

You need this because the ASP.NET Core authentication handler tries to instantiate your custom type from the container, as you can see in the code on GitHub.

Also, if the CustomJwtBearerEvents class has constructor dependencies, those also need to be registered in the DI container.

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.