0

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%20can%20create%20an%20helper%20class%20like%20this%20one%3A

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry if this is a noob question but what does the "Type" represent here in an IEnumerable? I see Claims having a list of 19 objects and was not sure what Type means.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.