本地登录后 User.Identity.Name 为空



我将IdentityServer4配置为使用AspNet Identity(.net core 3.0(,以便允许用户进行身份验证(登录名/密码(。

我的第三个应用程序是.net core 3.0中的 WebApi。

记录后,身份验证和授权成功,但我无法通过空/空 User.Identity.Name 检索 UserId。

但是,我可以看到包含包含 userId 的sub声明的声明信息。

这是我用于 IdentityServer4 Web 应用程序的软件包

PackageReference Include="IdentityServer4" Version="3.0.1" />

我遇到了同样的问题,我找到了两个解决方案。

  • [解决方案 1] - WebAPI - 更新 NameClaimIdentity Server 身份验证的类型 配置

在 WebAPI 的启动文件中,更新 NameClaimType 属性

services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.CacheDuration = xxxxx;
options.Authority = xxxxx;
options.ApiName = xxxx;
options.ApiSecret = xxxxx;
options.RequireHttpsMetadata = xxxxxx;
options.NameClaimType = JwtClaimTypes.Subject;
});
  • [解决方案 2] - IdentityServer4 应用程序 - 创建新的应用程序以自定义您的声明

为 IdentityServer4 服务器创建新的 profil,以便在令牌内自定义声明。

public class AspNetIdentityProfileService : IProfileService
{
private readonly IUserClaimsPrincipalFactory<ApplicationUser> _claimsFactory;
private readonly UserManager<ApplicationUser> _userManager;
public AspNetIdentityProfileService(UserManager<ApplicationUser> userManager, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory)
{
_userManager = userManager;
_claimsFactory = claimsFactory;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var sub = context.Subject.GetSubjectId();
var user = await _userManager.FindByIdAsync(sub);
var principal = await _claimsFactory.CreateAsync(user);
var claims = principal.Claims.ToList();
claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();
claims.Add(new Claim("name", user.UserName));
context.IssuedClaims = claims;
}
public async Task IsActiveAsync(IsActiveContext context)
{
var sub = context.Subject.GetSubjectId();
var user = await _userManager.FindByIdAsync(sub);
context.IsActive = user != null;
}
}

在启动文件中

services.AddTransient<IProfileService, AspNetIdentityProfileService>();

最新更新