1

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?

mode777
  • 3,037
  • 2
  • 23
  • 34

2 Answers2

1

Have you tried this for your authorize attribute:

[Authorize(ClaimTypes.Role, "Admin")]
Verthosa
  • 1,671
  • 1
  • 15
  • 37
  • Thanks, but there is no such Constructor for the AuthorizeAttribute in System.Web.Http, Version=5.2.3.0 – mode777 May 18 '17 at 11:42
  • 1
    If your issue isn't fixed yet, you can write a custom authorize attribute by inheriting from System.Web.Mvc.AuthorizeAttribute and check your claims 'manually' – Verthosa May 18 '17 at 13:35
  • Thats exactly what I was trying to avoid but ended up doing anyway :) – mode777 May 18 '17 at 15:33
1

This works for me:

var сlaimsIdentity = user.Identity as ClaimsIdentity;
сlaimsIdentity?.AddClaim(new Claim(сlaimsIdentity.RoleClaimType, "Admin"));
if (user.IsInRole("Admin")) ... // always true