我有一个使用 .NET Core 3.1 的应用程序,还有一个使用由此生成的默认 React 应用程序的前端link.
在 .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>();
创建自定义配置文件服务以将自定义声明包含到令牌和用户信息端点中:
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
以获得新的索赔。此外,角色声明也包含在访问令牌中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)