Angular 7和.Net Core Web api中的Azure AD身份验证和自定义角色库授权

问题描述 投票:-1回答:1

我想使用Azure AD进行身份验证,并希望在angular 7和.Net Core Web API中使用基于自定义角色的授权。我能够通过msal使用Azure AD成功验证用户身份,但是为了获得授权,我必须使用定义到数据库中的角色。我还需要将令牌中的角色传递回有角应用程序,以便我也可以在有角侧使用角色。

angular authentication azure-active-directory authorization asp.net-core-webapi
1个回答
0
投票
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

但是如果您的角色信息保存在本地数据库中,则在用户使用角度应用程序中的MSAL通过AAD和MSAD登录后,您可以查询数据库并通过用户ID获取用户的角色,执行api调用时,可以在请求正文中发送角色。 >

如果您不想在客户端应用程序中查询角色,则在将访问令牌发送到.net核心Web api时,可以查询数据库以在OnTokenValidatedAddJwtBearer事件中获取用户的角色:

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/

© www.soinside.com 2019 - 2024. All rights reserved.