我有一个使用.NET Core 3.1的应用程序,还有一个使用从此链接生成的默认React应用程序的前端。
在.NET Core应用程序中,我具有用户和角色的Identity Server安装程序。
当我在React应用程序中时,我想了解用户的角色。我看到当前正在使用一个名为的库oidc-client
。
从授权用户时我可以调试的响应中,我看到返回了一些范围。
scope: "openid profile [Name of the app]"
这是完整的回复。
我如何知道该用户的角色?我是否需要将其添加到.NET Core应用程序中的某个位置?还是可以从access_token
响应中找到答案?
该模板使用ASP.NET Core Identity管理用户/角色。首先要启用角色:
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
创建自定义配置文件服务以将自定义声明包含到令牌和userinfo端点中:
public class ProfileService : IProfileService
{
protected readonly UserManager<ApplicationUser> _userManager;
public ProfileService(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
ApplicationUser user = await _userManager.GetUserAsync(context.Subject);
IList<string> roles = await _userManager.GetRolesAsync(user);
IList<Claim> roleClaims = new List<Claim>();
foreach (string role in roles)
{
roleClaims.Add(new Claim(JwtClaimTypes.Role, role));
}
//add user claims
roleClaims.Add(new Claim(JwtClaimTypes.Name, user.UserName));
context.IssuedClaims.AddRange(roleClaims);
}
public Task IsActiveAsync(IsActiveContext context)
{
return Task.CompletedTask;
}
}
并在Startup.cs中注册:
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>()
.AddProfileService<ProfileService>();
现在,声明将包含在userinfo端点中,您的React应用程序将自动请求userinfo端点获取文件getUser
功能中的用户个人资料AuthorizeService.js
,并跟踪_user.profile
以获得新的声明。同样,角色声明也包含在访问令牌中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句