Fel*_*eña 4 single-page-application reactjs .net-core asp.net-core .net-core-3.0
我有一个使用 .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>();
Run Code Online (Sandbox Code Playgroud)
Crating 自定义 Profile 服务以将自定义声明包含到令牌和 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;
}
}
Run Code Online (Sandbox Code Playgroud)
并在 Startup.cs 中注册:
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>()
.AddProfileService<ProfileService>();
Run Code Online (Sandbox Code Playgroud)
现在声明将包含在 userinfo 端点中,您的反应应用程序将自动请求 userinfo 端点以获取用户的文件getUser功能 的配置AuthorizeService.js文件,跟踪_user.profile以获取新声明。此外,角色声明包含在访问令牌中。
| 归档时间: |
|
| 查看次数: |
749 次 |
| 最近记录: |