Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 358
Alberto López Avatar asked Oct 04 '15 07:10

Alberto López


1 Answers

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
like image 106
Marc Rubiño Avatar answered Dec 15 '22 16:12

Marc Rubiño