如何通过使用JWT Bearer令牌获取用户声明

时间:2019-01-29 14:05:45

标签: c# claims-based-identity httpcontext bearer-token

正在从邮递员的标头中发送承载者令牌。现在,我需要使用该承载令牌在API中获取用户声明。我尝试的代码无法正常工作,意味着没有获取用户名/电子邮件。如何使用Bearer Token获得用户声明?

public class RepositoryUserAccount : IRepositoryUserAccount
{
    private readonly HttpContext _httpContext;

    public RepositoryUserAccount(IHttpContextAccessor httpContextAccessor)
    {
        this._httpContext = httpContextAccessor.HttpContext;
    }

    public async Task EnableAuthenticator()
    {
        ClaimsPrincipal currentUser = _httpContext.User;
        var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
    }
}

3 个答案:

答案 0 :(得分:0)

我们假设System.Security.Claims.ClaimTypes是身份验证

var claims = _httpContext.User.Claims.Where(x => x.Type == ClaimTypes.Authentication);
foreach (var claim in claims)
{
    var value = claim.Value; //<= the value of each claim
}

答案 1 :(得分:0)

您正在按照评论中的说明将其注册为单例。重构该类以使其每次使用IHttpContextAccessor或将其更改为传递依赖。

第一种方法:

public class RepositoryUserAccount : IRepositoryUserAccount
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public RepositoryUserAccount(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public async Task EnableAuthenticator()
    {
        ClaimsPrincipal currentUser = _httpContextAccessor.HttpContext.User;
        var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
    }
}

答案 2 :(得分:0)

我所做的是,在启动时,我将服务配置为

var key = Encoding.ASCII.GetBytes(SECRET_KEY);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

在控制器中,我确实喜欢

[HttpGet]
[Route("EnableAuthenticator")]
public void EnableAuthenticator()
{
   var user = HttpContext.User;
}

在用户中,我们将获得所有索赔。就是这样!