如何只添加令牌确认为保护行动ASP.NET 5(ASP.NET睿) [英] How to add token validation only for protected actions in ASP.NET 5 (ASP.NET Core)

查看:237
本文介绍了如何只添加令牌确认为保护行动ASP.NET 5(ASP.NET睿)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have added a JWT middleware to my application:

app.UseJwtBearerAuthentication(options => { options.AutomaticAuthenticate = true;} )

现在,如果我的令牌不验证(例如过期),我仍然得到一个错误,一辈子验证未通过。有没有一种方法,使中间件验证令牌只对受保护的资源?如果没有,那么如何以及在哪里我应该叫什么呢中间件自己(读令牌插入HttpContext.User中)?

Now if my token does not validate (e.g. expired), I still get an error that lifetime validation did not pass. Is there a way to make the middleware validate the token only for protected resources? And if not, then how and where should I call what middleware does myself (reading the token into HttpContext.User)?

P.S这是我怎么加保护:

P.S This is how I add protection:

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

            config.Filters.Add(new AuthorizeFilter(policy));
        });

和我这是怎么让公众访问:

And this is how I allow public access:

    [HttpGet]
    [AllowAnonymous]
    public string Get(int id)
    {

    }

要澄清:没有令牌这会工作,但如果令牌是无效的(如过期)即使是公共资源将无法访问和500将被抛出(由于一些内部原因的错误401应该是真的)。

To clarify: without the token this will work, but if the token is not valid (e.g. expired) even the public resource won't be accessible and 500 will be thrown (due to some internal bug cause 401 should be there really).

推荐答案

首先,你需要通过设置来禁用自动认证的 AutomaticAuthentication 的在智威汤逊承载选项。

First, you need to disable automatic authentication by setting AutomaticAuthentication to false in your JWT bearer options.

要确保JWT承载中间件要求的具体行动,您可以使用创建自己的授权策略的 AddAuthenticationSchemes

To ensure the JWT bearer middleware is called for specific actions, you can create your own authorization policy using AddAuthenticationSchemes:

public void ConfigureServices(IServiceCollection services) {
    services.AddAuthorization(options => {
        options.AddPolicy("API", policy => {
            policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
            policy.RequireAuthenticatedUser();
        });
    });
}

接着,使用授权属性修饰你的控制器操作:

Then, decorate your controller actions with the Authorize attribute:

[Authorize(Policy = "API")]
[HttpGet("your-action")]
public IActionResult Action() {
    ...
}

这篇关于如何只添加令牌确认为保护行动ASP.NET 5(ASP.NET睿)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆