相关疑难解决方法(0)

如何仅为ASP.NET 5中的受保护操作添加令牌验证(ASP.NET Core)

我在我的应用程序中添加了一个JWT中间件:

app.UseJwtBearerAuthentication(options => { options.AutomaticAuthenticate = true;} )
Run Code Online (Sandbox Code Playgroud)

现在,如果我的令牌未验证(例如已过期),我仍然会收到生命周期验证未通过的错误.有没有办法让中间件仅为受保护资源验证令牌?如果没有,那么我应该如何以及在哪里调用自己的中间件(将令牌读入HttpContext.User)?

PS这是我添加保护的方式:

services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();

    config.Filters.Add(new AuthorizeFilter(policy));
});
Run Code Online (Sandbox Code Playgroud)

这就是我允许公共访问的方式:

[HttpGet]
[AllowAnonymous]
public string Get(int id)
{
}
Run Code Online (Sandbox Code Playgroud)

澄清:如果没有令牌,这将有效,但如果令牌无效(例如已过期),即使公共资源将无法访问,也会抛出500(由于某些内部错误导致401应该真的存在).

authentication oauth jwt openid-connect asp.net-core

5
推荐指数
1
解决办法
1489
查看次数