繁体   English   中英

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

[英]Azure AD authentication and Custom Role base authorization in Angular 7 and .Net Core Web api

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

在 Azure AD 中,您可以在应用程序中使用添加应用角色,然后将用户和组分配给角色,这样用户登录后,角色 cliam 将存在于令牌中:

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核心Web API时,你可以查询数据库来获取用户的角色中OnTokenValidated的事件AddJwtBearer

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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM