如何在 Asp.net Web Api 2 - Owin - ApiController 中获取自定义声明值。
How to get custom claims value in Asp.net Web Api 2 - Owin - ApiController.
我使用此代码创建了一些声明,我在登录应用程序时获得了这些值。我想在我的一些 api 控制器中使用 "Id" 的声明值,
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(门票);
所以在控制器中我有这个代码:
[Authorize]
[Route("api/banners/{customerId")]
[HttpGet]
public HttpResponseMessage GetBanners(int customerId)
{
return Request.CreateResponse<IEnumerable<Banner>>(HttpStatusCode.OK, AppDataAccess.GetBanners(customerId)));
}
我想把代码改成这个:
[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)));
}
我一直在研究,但我刚刚找到了 AuthorizationFilterAttribute,但它只是在路线上使用它,有没有什么方法你知道我可以构建那个函数,所以我只是在控制器中调用它?
我正在使用 Microsoft.AspNet.Identity.Owin 2.0.0
感谢帮助
像这样保存您的自定义声明:
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim("Id", user.Id.ToString()));
然后像这样:
((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(x => x.Type == "Id").Value
我使用此代码创建了一些声明,我在登录应用程序时获得了这些值。我想在我的一些 api 控制器中使用 "Id" 的声明值,
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(门票);
所以在控制器中我有这个代码:
[Authorize]
[Route("api/banners/{customerId")]
[HttpGet]
public HttpResponseMessage GetBanners(int customerId)
{
return Request.CreateResponse<IEnumerable<Banner>>(HttpStatusCode.OK, AppDataAccess.GetBanners(customerId)));
}
我想把代码改成这个:
[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)));
}
我一直在研究,但我刚刚找到了 AuthorizationFilterAttribute,但它只是在路线上使用它,有没有什么方法你知道我可以构建那个函数,所以我只是在控制器中调用它?
我正在使用 Microsoft.AspNet.Identity.Owin 2.0.0
感谢帮助
像这样保存您的自定义声明:
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim("Id", user.Id.ToString()));
然后像这样:
((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(x => x.Type == "Id").Value