Get claims from a WebAPI Controller - JWT Token,

后端 未结 4 1939
一向
一向 2020-12-05 18:53

I have built an application which uses JWT bearer authentication in ASP.NET Core. When authenticating I define some custom claims which i need to read in another WebAPI con

4条回答
  •  悲&欢浪女
    2020-12-05 19:12

    // Cast to ClaimsIdentity.
    var identity = HttpContext.User.Identity as ClaimsIdentity;
    
    // Gets list of claims.
    IEnumerable claim = identity.Claims; 
    
    // Gets name from claims. Generally it's an email address.
    var usernameClaim = claim
        .Where(x => x.Type == ClaimTypes.Name)
        .FirstOrDefault();
    
    // Finds user.
    var userName = await _userManager
        .FindByNameAsync(usernameClaim.Value);
    
    if (userName == null)
    {
        return BadRequest();
    }
    
    // The rest of your code goes here...
    

提交回复
热议问题