PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 4, 2022

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

 September 04, 2022     .net-core, asp.net-core-webapi, authentication, azure-active-directory, c#     No comments   

Issue

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


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


Answered By - Okan Karadag
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing