Getting Custom User Claims in the ApiController - ASP.net

To get access to all the claims for a User in API Controller method, you will need to cast the User.Identity to Claims Identity like so:

[Authorize]
public class ValuesController : ApiController
{

    // GET api/values
    public IEnumerable<string> Get()
    {

        var identity = (System.Security.Claims.ClaimsIdentity)User.Identity;

        string email = string.Empty;
        var emailClaim = identity.Claims.Where(x => x.Type == "Email");
        if (emailClaim.Any())
            email = emailClaim.First().Value;

        return new string[] { "value1", "value2", User.Identity.Name, .IsInRole("User").ToString(), User.IsInRole("Administrator").ToString(), email };

    }


Comments