Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading