我一直试图用AspNetIdentity设置一个新的IdentityServer3几天了。我可以使用我现有的Identity DB登录,这一切都很好,但我永远无法获得User.Identity.Name来包含数据。我尝试过多次尝试添加自定义声明和范围以及向客户端添加范围。
最后,我加载了IdentityServer3示例存储库,并使用webforms客户端项目对其进行了测试,因为它已在其“关于”页面中使用了User.Identity.Name。
使用WebForms示例客户端+ AspNetIdentity示例服务器= User.Identity.Name始终为null使用带有Seq示例服务器的WebForms示例客户端+ SelfHost =带有数据的User.Identity.Name我尝试了其他所有填充User.Identity的示例宿主项目.Name值就好了。
现在,在客户端,我写了一个解决方法来提取'preferred_username'声明值并用它设置'name'声明。
var id = new claimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
id.AddClaims(userInfoResponse.GetClaimsIdentity().Claims);
//set the User.Identity.Name value
var name = id.Claims.Where(x => x.Type == "name").Select(x => x.Value).FirstOrDefault() ??
id.Claims.Where(x => x.Type == "preferred_username").Select(x => x.Value).FirstOrDefault();
id.AddClaim(new Claim("name", name));
我的问题是:
public static IEnumerable<ApiResource> GetApis()
{
return new ApiResource[]
{
new ApiResource("MyApi", "My Admin API")
{
UserClaims = { JwtClaimTypes.Name, JwtClaimTypes.Email }
}
};
}
在Identityserver4中,您可以将UserClaims添加到资源中。为我修好了。
在IdentityServer4上,您可以在服务器上实现IProfileService,并在GetProfileDataAsync中添加Claim
public class AspNetIdentityProfileService : IProfileService
{
protected UserManager<ApplicationUser> _userManager;
public AspNetIdentityProfileService(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
//Processing
var user = _userManager.GetUserAsync(context.Subject).Result;
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
};
context.IssuedClaims.AddRange(claims);
//Return
return Task.FromResult(0);
}
public Task IsActiveAsync(IsActiveContext context)
{
//Processing
var user = _userManager.GetUserAsync(context.Subject).Result;
context.IsActive = (user != null) && ((!user.LockoutEnd.HasValue) || (user.LockoutEnd.Value <= DateTime.Now));
//Return
return Task.FromResult(0);
}
}
然后将“AddProfileService()”添加到ConfigureServices方法。
services.AddIdentityServer(...)
...
.AddProfileService<AspNetIdentityProfileService>();