在Azure AD中,你可以在你的应用程序中使用add app roles,然后将用户和组分配给角色,这样用户登录后,角色cliam就会存在于token中:
https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps
另一种方法是使用 Azure AD 组和组声明:
https://docs.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-fed-group-claims
但是如果你的角色信息保存在本地数据库中,用户在 Angular 应用程序中使用 MSAL 使用 AAD 登录后,可以通过用户 id 查询数据库并获取用户角色,在执行 api 调用时,可以在请求正文中发送角色。
如果您不想在客户端应用程序中查询角色,则在向.net core web api发送访问令牌时,您可以在AddJwtBearer的OnTokenValidated事件中查询数据库以获取用户的角色:
services
.AddAuthentication(o =>
{
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
//Additional config snipped
o.Events = new JwtBearerEvents
{
OnTokenValidated = async ctx =>
{
//Get the calling app client id that came from the token produced by Azure AD
string clientId = ctx.Principal.FindFirstValue("appid");
//Get EF context
var db = ctx.HttpContext.RequestServices.GetRequiredService<AuthorizationDbContext>();
//Check if this app can read confidential items
bool canReadConfidentialItems = await db.Applications.AnyAsync(a => a.ClientId == clientId && a.ReadConfidentialItems);
if (canReadConfidentialItems)
{
//Add claim if yes
var claims = new List<Claim>
{
new Claim("ConfidentialAccess", "true")
};
var appIdentity = new ClaimsIdentity(claims);
ctx.Principal.AddIdentity(appIdentity);
}
}
};
});
参考:https://joonasw.net/view/adding-custom-claims-aspnet-core-2
之后,您可以在请求正文中将角色传递回客户端,但不能修改 Azure AD 令牌以包含角色信息。
如果您担心在请求正文中传递角色的安全性,您还可以使用 Identity Server 4 并将 Azure AD 添加为外部登录提供程序:
http://docs.identityserver.io/en/latest/