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?
options.Events = new JwtBearerEvents { }. Then you can use IntelliSense to figure out what event properties are available there :)