Search code examples
asp.net-web-apiasp.net-coreclaims-based-identityclaims

How to add values to claims and retrieve it from web api - .Net core


I am using Asp .net core 2.1

How to add custom claims after login?


Solution

  • in order to add custom claims after login, you can use the AddClaim method over a new ClaimsIdentity instance

    var claims = new List<Claim>();
    claims.Add(new Claim(ClaimTypes.Name, "some Name"));
    claims.Add(new Claim(ClaimTypes.Email, "abc@xyz.com"));
    var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
    
    var ctx = Request.GetOwinContext();
    var authenticationManager = ctx.Authentication;
    authenticationManager.SignIn(identity);
    

    Then to retrieve the claims, you can use the LINQ over the ClaimsPrincipal instance:

    var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
    string email = identity.Claims.Where(c => c.Type == ClaimTypes.Email).Select(c => c.Value).SingleOrDefault();
    

    Update: While trying to explore and fix the issue myself, I found this answer which works as an alternate solution to your problem.