asp.net-identity - 本地登录后 User.Identity.Name 为空
问题描述
我配置IdentityServer4
为使用 AspNet Identity (.net core 3.0) 以允许用户进行身份验证(登录名/密码)。
我的第三个应用程序是.net core 3.0
.
登录后,身份验证和授权成功,但我无法通过为空/空的 User.Identity.Name 检索 UserId。
但是,我可以看到包含sub
包含 userId 的声明的声明信息。
这是我用于 IdentityServer4 Web 应用程序的包
PackageReference Include="IdentityServer4" Version="3.0.1" />
解决方案
我面临同样的问题,我找到了两个解决方案。
- [解决方案 1] - WebApi - 更新 IdentityServerAuthentication 配置的 NameClaimType
在 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 App - 创建新的配置文件以自定义您的声明
为 IdentityServer4 服务器创建一个新的配置文件,以便自定义令牌内的声明。
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>();
推荐阅读
- javascript - 如何使用 Google Analytics 设置 Reactjs?
- python - 根据另一列特定值用平均值填充 NaN 值
- python - django 和 html 上的 ml 模型
- python-3.x - 向用户数据添加新的 openTypeExtension 的后调用失败,并显示“找不到段'扩展'的资源”
- function - 如何从另一个模块中的函数(方法)中访问变量
- c++ - vcpkg:回想起安装软件包后显示的 CMake 说明?
- azure-active-directory - Azure AD + Microsoft 帐户应用程序中缺乏组合同意的解决方法/缺点
- android - Cucumber:是否可以从 android 设备上的文件夹中读取 .feature 文件?
- powerbi - 是否可以从 Azure DevOps 外部可视化 Sprint 燃尽图(或燃尽图)?
- sharepoint - 使用正确的列表项 ID 将数据从一个列表添加到另一个列表 SharePoint