5

I have a Web API with a POST method like this:

[HttpPut]
[Authorize("FeaturePolicy")]
public IActionResult Put()
{             
  return Ok();
}

And the start up looks like this:

public void ConfigureServices(IServiceCollection services)
{
   services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
   services.AddAuthentications();
   services.AddAuthorization("FeaturePolicy", "featureId");
} 

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }
  else
  {
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see   https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
  }        
    app.UseHttpsRedirection();
    app.UseMvc();
    app.UseAuthentication();
}

I am sending the JWT Token bearer from the Postman as headers. When I try to access the claims from HandleRequirementAsync handler, the claims come empty. The handler looks like:

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, 
                                                       FeatureRequirement requirement)
{
  var identity = (ClaimsIdentity)context.User.Identity;
  IEnumerable<Claim> claims = identity.Claims;
  context.Succeed(requirement);
}

Am doing something wrong here? Please help! Thanks.

Eldho John
  • 71
  • 7
  • If you are not getting a successful Identity authenticated then your context won't have the claims inside. I mean your problem is that the request cannot be authenticated. Your request does not have rights to be done – gogoru May 23 '20 at 10:57

2 Answers2

0

If You want to have Claim You Should declare it (settings of Jwt)

Like Below:

   private string generateJwtToken(User user)
    {
        // generate token that is valid for 7 days
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }),
            Expires = DateTime.UtcNow.AddDays(7),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }
Ramin Azali
  • 198
  • 11
0

You should put app.UseAuthentication() above app.UseMvc() as stated in this thread: https://stackoverflow.com/a/61523579/14010438