How to add token validation only for protected actions in ASP.NET 5 (ASP.NET Core)

試著忘記壹切 提交于 2019-12-05 10:28:50

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

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() {
    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!