Search code examples
asp.net-web-api2claims-based-identityasp.net-identity-2

How to get custom claims value in Asp.net Web Api 2 - Owin - ApiController.


I create some Claims with this code, I am getting the values when I log in the app. I want to use the claim value of "Id" in some of my api controllers,

var identity = new ClaimsIdentity(context.Options.AuthenticationType);

var props = new AuthenticationProperties(new Dictionary<string, string>
{
    { "UserName", customer.FirstName }, { "Id", customer.Id.ToString() } 
});

var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket);

So in the controller I have this code:

[Authorize]
[Route("api/banners/{customerId")]
[HttpGet]
public HttpResponseMessage GetBanners(int customerId)
{
    return Request.CreateResponse<IEnumerable<Banner>>(HttpStatusCode.OK, AppDataAccess.GetBanners(customerId)));
}

And I would like to change the code to this one:

[Authorize]
[Route("api/banners")]
[HttpGet]
public HttpResponseMessage GetBanners()
{ 
   int CustomerId =  SOME FUNCTION THAT GETS THE CLAIM VALUE I WANT (ID)

    return Request.CreateResponse<IEnumerable<Banner>>(HttpStatusCode.OK, AppDataAccess.GetBanners(customerId)));
}

I have been researching but I just found the AuthorizationFilterAttribute but it just works using it on the route, Is there any way that you know I could build that function so I just call it in the controller??

I am using Microsoft.AspNet.Identity.Owin 2.0.0

Thanks for the help


Solution

  • Save your custom claims like this:

     var identity = new ClaimsIdentity(context.Options.AuthenticationType);
     identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     identity.AddClaim(new Claim("Id", user.Id.ToString()));
    

    And get like this:

     ((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(x => x.Type == "Id").Value