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

I added the JWT middleware to my application:

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

Now, if my token does not check (for example, expired), I still get an error message that has not been checked for life. Is there a way to make the middleware check the token only for secure resources? And if not, how and where should I name what the middleware does (read the token in HttpContext.User)?

PS This is how I add protection:

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

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

And I allow public access:

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

To clarify: without a token, this will work, but if the token is invalid (for example, expired), even a public resource will not be available, and 500 will be thrown out (due to some internal error, error 401 should really be there).

+4
1

-, , AutomaticAuthentication false - JWT.

JWT , AddAuthenticationSchemes:

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

, Authorize:

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

Source: https://habr.com/ru/post/1625848/


All Articles