我正在尝试对要在我的API上“公开”的方法跳过令牌验证。
在启动中,我收到以下事件,以检查呼叫是否被授权:
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);
});
}
}
};
我尝试从控制器中删除[Authorize]
属性,但上述代码仍会触发
还尝试在我要跳过验证但仍然是上述代码触发器的方法上添加[IgnoreAntiforgeryToken(Order = 1001)]
。
您知道如何仅对某些方法禁用它吗?
答案 0 :(得分:1)
通常,您要装饰要允许使用[AllowAnonymous]
不进行身份验证的控制器或操作(请参见docs)。
如果您具有多个身份验证(Jwt,Cookie),并且只希望特定端点仅允许特定身份验证,则可以使用scheme属性,即[Authorize(Scheme = "Cookie)]
。
答案 1 :(得分:0)
如果端点实现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);
});
}
}
};