1

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()
    {
       .......
    }
Steve Holland
  • 609
  • 1
  • 12
  • 29
Avesh Naik
  • 179
  • 1
  • 11

1 Answers1

0

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 AuthorizeAttributes 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.

Community
  • 1
  • 1
Tseng
  • 52,202
  • 10
  • 166
  • 183
  • Well i don't want to allow users who doesn't own a token. if i removed Authorize attribute i will allow users to access. But i don't want users who doesn't submit token – Avesh Naik Feb 27 '16 at 11:59
  • Users without a token (or an expired one) are by definition unauthorized. That's the standard behavior of `Authorize`, why would you need a custom policy for it? Maybe clarify your question – Tseng Feb 27 '16 at 12:02
  • @AveshNaik: See my updated question. What you ask is a standard behavior, but your usage seems wrong. Try simply using the `AddAuthentication` call without any policy. I also added a link to an SO answer that shows how to correctly use Policies to i.e. verify the age of the user – Tseng Feb 27 '16 at 13:03
  • I tried the default behavior but it still give me 401 error even if i have Access Token – Avesh Naik Feb 27 '16 at 18:18
  • @AveshNaik: You got to post the log output from the console. I suspect your token may be invalid or expired, invalid issuer or audience. Each of this should throw an exception in the console window or in your logfile if you added a file logger – Tseng Feb 27 '16 at 18:23