简体   繁体   中英

Token Authentication Using Policy Base in Asp.net core / 5

I am sending Token from client side to server as

"Authorization: Bearer eyJhbGciOiJodHR......"

i want to Authorize users who have tokens here is my code.

services.AddAuthorization(auth =>
{
    auth.AddPolicy("Have", new AuthorizationPolicyBuilder()                                 
    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
    .RequireAuthenticatedUser().Build());
 });



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




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

Even if i turn AutomaticAuthenticate i get 500 error if false then 401 error

    [Authorize(Policy ="Have")]
    [HttpGet]
    [Route("list")]
    public IEnumerable<Products> List()
    {
       .......
    }

For this behavior you don't need any special policy or configuration, because it's the default behavior to only allow access to authorized users. Users with no token or expired token are unauthorized and won't be able to access controllers/actions with an [Authorize] attribute.

All you need is

services.AddAuthentication();

and AuthorizeAttribute s on your actions/controllers.

Policies are only here to validate conditions of authorized users , for example if the user is at at the age of 18 or older (see this answer for an example), where his birthday is one of the user's claims.

If a user is not authorized, the policy will never be validated. This means Authorize will always fail and deny access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM