UseJwtBearerAuthentication不会填充User.Identity.Name [英] UseJwtBearerAuthentication does not get User.Identity.Name populated

查看:194
本文介绍了UseJwtBearerAuthentication不会填充User.Identity.Name的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JWT用于ASP.NET Core Web API项目中的身份验证机制.假设该项目没有MVC部分,并且不使用cookie身份验证.我已经基于

I am trying to use JWT for authentication mechanism in ASP.NET Core Web API project. Suppose this project has not MVC part and does not use cookie authentication. I have created my code based on this guide.

登录正常,使用[Authorize]属性进行保护也可以,但是User.Identity.Namenull.我该如何解决?

Login works good and protection with [Authorize] attribute works ok but User.Identity.Name is null. How can I fix this?

我的代码:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
    var tokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

        ValidateAudience = true,
        ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

        ValidateIssuerSigningKey = true,
        IssuerSigningKey = _signingKey,

        RequireExpirationTime = true,
        ValidateLifetime = true,

        ClockSkew = TimeSpan.Zero
    };

    app.UseJwtBearerAuthentication(new JwtBearerOptions
    {
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        TokenValidationParameters = tokenValidationParameters,
        AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}


    [HttpPost]
    [AllowAnonymous]
    [Route("Login")]
    public async Task<IActionResult> Login([FromForm] ApplicationUser applicationUser)
    {
        //assume user/pass are checked and are ok

        _logger.LogInformation(1, "API User logged in.");
        var user = await _userManager.FindByNameAsync(applicationUser.UserName);
        var roles = await _userManager.GetRolesAsync(user);

        var claims = new List<Claim>
        {
            new Claim(JwtRegisteredClaimNames.Sub, applicationUser.UserName),
            new Claim(ClaimTypes.NameIdentifier, applicationUser.UserName),
            new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
            new Claim(JwtRegisteredClaimNames.Iat,
                    ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(),
                    ClaimValueTypes.Integer64),
                    new Claim("Claim", "Value")
        };

        if (roles != null)
            foreach (var role in roles)
                claims.Add(new Claim("role", role));

        // Create the JWT security token and encode it.
        var jwt = new JwtSecurityToken(
            issuer: _jwtOptions.Issuer,
            audience: _jwtOptions.Audience,
            claims: claims,
            notBefore: _jwtOptions.NotBefore,
            expires: _jwtOptions.Expiration,
            signingCredentials: _jwtOptions.SigningCredentials);

        var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

        // Serialize and return the response
        var response = new
        {
            access_token = encodedJwt,
            expires_in = (int)_jwtOptions.ValidFor.TotalSeconds
        };

        var json = JsonConvert.SerializeObject(response, _serializerSettings);
        return new OkObjectResult(json);
    }

推荐答案

在您的声明中(第二代码段),我只能看到以下内容:

in your claims (second code snippet) I can only see this:

new Claim(ClaimTypes.NameIdentifier, applicationUser.UserName),

但是您需要添加以下内容:

but you need to add this:

new Claim(ClaimTypes.Name, applicationUser.UserName),

然后,User.Identity.Name应该包含用户名.

then User.Identity.Name should contain the username.

这篇关于UseJwtBearerAuthentication不会填充User.Identity.Name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆