gpt4 book ai didi

authentication - UseJwtBearerAuthentication 没有填充 User.Identity.Name

转载 作者:行者123 更新时间:2023-12-03 07:32:22 25 4
gpt4 key购买 nike

我正在尝试使用 JWT用于身份验证机制 ASP.NET Core Web API项目。假设这个项目没有 MVC部分并且不使用 cookie 身份验证。我已经基于 this guide 创建了我的代码.

使用 [Authorize] 登录效果良好并提供保护属性工作正常,但 User.Identity.Namenull .我怎样才能解决这个问题?

我的代码:

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);
}

最佳答案

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

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

但你需要添加这个:
new Claim(ClaimTypes.Name, applicationUser.UserName),

那么 User.Identity.Name 应该包含用户名。

关于authentication - UseJwtBearerAuthentication 没有填充 User.Identity.Name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41830898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com