Reputation: 3197
I want to add a role claim to an already authenticated windows user. My naive first approach was to add the role claim inside of a custom owin middleware which runs before WebApi. Like this:
public class IdentityMiddleware : OwinMiddleware
{
public IdentityMiddleware(OwinMiddleware next) : base(next)
{
}
public async override Task Invoke(IOwinContext context)
{
var user = context.Request.User as WindowsPrincipal;
var identity = user.Identity as ClaimsIdentity;
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
await Next.Invoke(context);
}
}
However when providing the Authorize attribute in the controller like this.
public class TestController : ApiController
{
[Authorize(Roles = "Admin")]
public string Get()
{
return User.Identity.Name;
}
}
..I will get a 401.
I noticed that the issuer of the new claim is "Local Authority" instead of "AD Authority" could this be the reason?
Upvotes: 1
Views: 1625
Reputation: 350
This works for me:
var сlaimsIdentity = user.Identity as ClaimsIdentity;
сlaimsIdentity?.AddClaim(new Claim(сlaimsIdentity.RoleClaimType, "Admin"));
if (user.IsInRole("Admin")) ... // always true
Upvotes: 1
Reputation: 1688
Have you tried this for your authorize attribute:
[Authorize(ClaimTypes.Role, "Admin")]
Upvotes: 1