Reputation: 26737
I'm trying to skip the token validation for a methods I want to make "public" on my API.
In my StartUp I got the below event to check if a call is authorized:
x.Events = new JwtBearerEvents
{
OnTokenValidated = async context =>
{
var sessionManager = context.HttpContext.GetService<ISessionManager>();
if (!sessionManager.IsCurrentTokenValid())
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
var message = Encoding.UTF8.GetBytes("invalidToken");
context.Response.OnStarting(async () =>
{
await context.Response.Body.WriteAsync(message, 0, message.Length);
});
}
}
};
I've tried to remove [Authorize]
attribute form the controller but the above code still triggers
Also tried to add [IgnoreAntiforgeryToken(Order = 1001)]
on the method I want to skip the validation but still the above code triggers.
Do you know how can I disable it only for certain methods ?
Upvotes: 2
Views: 3436
Reputation: 2909
Try to ignore token validation result if the the endpoint implements AllowAnonymous
x.Events = new JwtBearerEvents
{
OnTokenValidated = async context =>
{
var sessionManager = context.HttpContext.GetService<ISessionManager>();
var endpoint = context.HttpContext.Features.Get<IEndpointFeature>()?.Endpoint;
var allowAnon = endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null;
if (!allowAnon && !sessionManager.IsCurrentTokenValid())
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
var message = Encoding.UTF8.GetBytes("invalidToken");
context.Response.OnStarting(async () =>
{
await context.Response.Body.WriteAsync(message, 0, message.Length);
});
}
}
};
Upvotes: 1
Reputation: 64200
Usually you decorate controllers or actions which you want to allow w/o authentication with [AllowAnonymous]
(see docs).
If you have multiple authentications (Jwt, Cookie) and you want specific endpoints only allowed with a specific authentication, you use the scheme attribute, i.e. [Authorize(Scheme = "Cookie)]
.
Upvotes: 1