我的ASP中有以下配置:. NET Core Web API:
// Adds Microsoft Identity platform (AAD v2.0) support to protect this Api
services.AddMicrosoftIdentityWebApiAuthentication(configuration);
services.AddControllers(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireClaim("email")
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
我有一个Angular客户端应用,它会在每个请求中发送AuthToken。
下面是我的asp.net WEB API控制器[Route("[controller]")]
public class UserController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
//Get User Email ID from Claims
//Get User details from Database
//Return the User Details
...
}
}
在asp.net WEB API控制器中,我需要从AuthToken中获取Email声明。
如何在。net Core 3.1 Web API控制器中获得索赔?有需要遵循的最佳实践吗?
参考:https://stackoverflow.com/questions/68817413/how-to-get-user-information-after-login-in-asp-net-core3-1: ~:文本= % 20可以% 20创建% 20一个% 20助手% 20类% 20像% 20 % 20一个% 3
var identity = HttpContext.User.Identity as ClaimsIdentity;
var email = identity?.FindFirst("email")?.Value;
//or
var email2 = User.Claims.FirstOrDefault(x => x.Type == "email")?.Value