【问题标题】:Azure AD authentication and Custom Role base authorization in Angular 7 and .Net Core Web apiAngular 7 和 .Net Core Web api 中的 Azure AD 身份验证和自定义角色基础授权
【发布时间】:2020-05-25 02:45:10
【问题描述】:

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

【问题讨论】:

    标签: angular authentication azure-active-directory authorization asp.net-core-webapi


    【解决方案1】:

    在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发送访问令牌时,您可以在AddJwtBearerOnTokenValidated事件中查询数据库以获取用户的角色:

    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/

    【讨论】:

      猜你喜欢
      • 2017-01-23
      • 2021-11-26
      • 2020-07-27
      • 2021-02-21
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      相关资源
      最近更新 更多