I use an attribute [Authorize]in my WebAPI controller action and it always returns unauthorized.
Here is my action
[Authorize(Roles = "Admin")]
public IQueryable<Country> GetCountries()
{
return db.Countries;
}
Here I set authorization in the global MessageHandler. This is for testing. I put in a test user.
public class AuthenticationHandler1 : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
HttpContext.Current.User = TestClaimsPrincipal();
}
return base.SendAsync(request, cancellationToken);
}
private ClaimsPrincipal TestClaimsPrincipal()
{
var identity = new ClaimsIdentity(HttpContext.Current.User.Identity.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, "some.user"));
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));
var testIdentity = new ClaimsIdentity(identity);
var myPrincipal = new ClaimsPrincipal(testIdentity);
return myPrincipal;
}
}
Registered Global.asax.csinApplication_Start
GlobalConfiguration.Configuration.MessageHandlers.Add(new MyProject.AuthenticationHandler1());
He continues to show it for the message.
{"Message":"Authorization has been denied for this request."}
source
share