如何在Asp.net Web Api 2中获取自定义声明值 - Owin - ApiController.

alb*_*olo 3 claims-based-identity asp.net-web-api2 asp.net-identity-2

我使用此代码创建了一些声明,我在登录应用程序时获取了值.我想在我的一些api控制器中使用"Id"的声明值,

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

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

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

所以在控制器中我有这个代码:

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

我想将代码更改为此代码:

[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)));
}
Run Code Online (Sandbox Code Playgroud)

我一直在研究,但我刚刚找到了AuthorizationFilterAttribute,但它只是在路由上使用它,有没有什么方法你知道我可以构建该功能所以我只是在控制器中调用它?

我正在使用Microsoft.AspNet.Identity.Owin 2.0.0

谢谢您的帮助

小智 6

像这样保存您的自定义声明:

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

得到这样的:

 ((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(x => x.Type == "Id").Value
Run Code Online (Sandbox Code Playgroud)