从持有人令牌(Web API)获取自定义声明值

Imp*_*rks 18 asp.net claims-based-identity asp.net-web-api bearer-token

在我的ASP.NET Web API项目中,我使用了承载令牌授权,并且我添加了一些自定义声明,如下所示:

var authType = AuthConfig.OAuthOptions.AuthenticationType;
var identity = new ClaimsIdentity(authType);
identity.AddClaim(new Claim(ClaimTypes.Name, vm.Username));

// custom claim
identity.AddClaim(new Claim("CompanyID", profile.CompanyId.ToString()));
Run Code Online (Sandbox Code Playgroud)

有没有什么方法可以在控制器中访问这个额外的索赔值而无需额外访问数据库?

Tai*_*deh 29

当然,在受保护的控制器内,您可以执行以下操作:

 ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
 var customClaimValue = principal.Claims.Where(c => c.Type == "CompanyID").Single().Value;
Run Code Online (Sandbox Code Playgroud)