5

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

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.