Home > database >  How to get claims in .Net Core 3.1 Web API Controller?
How to get claims in .Net Core 3.1 Web API Controller?

Time:07-07

I have the following configuration in my 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));
});

I have an Angular client application that sends the AuthToken with each request.

Below is my asp.net WEB API controller

[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
        ...
    }
}

In the asp.net WEB API controller, I need to get the Email claim from the AuthToken.

How to get claims in .Net Core 3.1 Web API Controller ? Any best practices to be followed?

Reference: https://stackoverflow.com/questions/68817413/how-to-get-user-information-after-login-in-asp-net-core3-1#:~:text=You can create an helper class like this one:

CodePudding user response:

 var identity = HttpContext.User.Identity as ClaimsIdentity;
 var email = identity?.FindFirst("email")?.Value;
 //or
 var email2 = User.Claims.FirstOrDefault(x => x.Type == "email")?.Value
  • Related