确定SPA和.NET Core 3的角色 [英] Identify roles with SPA and .NET Core 3
本文介绍了确定SPA和.NET Core 3的角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用.NET Core 3.1的应用程序,还有一个使用从link生成的默认Reaction应用程序的前端。
在.NET Core应用程序中,我设置了具有用户和角色的Identity Server。当我在Reaction应用程序中时,我想知道用户的角色。我看到目前正在使用一个名为oidc-client
的库。
从授权用户时我可以调试的响应中,我看到返回了一些作用域。
scope: "openid profile [Name of the app]"
这是完整的回复。
我如何知道该用户的角色?
我是否需要将其添加到我的.NET Core应用程序中的某个位置?
或者我可以从回复中的access_token
算出来吗?
推荐答案
该模板使用ASP.NET核心标识来管理用户/角色。因此,第一件事是启用角色:
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终结点中,您的Reaction应用程序将自动请求UserInfo终结点在AuthorizeService.js
文件的getUser
函数中获取用户的配置文件,跟踪_user.profile
以获取新的声明。此外,角色声明包括在访问令牌中。
这篇关于确定SPA和.NET Core 3的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文