将应用程序角色作为自定义声明添加到Azure AD身份 [英] Add application roles as custom claims to Azure AD identities

查看:74
本文介绍了将应用程序角色作为自定义声明添加到Azure AD身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个webapp,它同时支持基于表单的身份验证(使用OOTB Asp.net身份框架)和基于Azure AD的身份验证(使用OpenID Connect).身份验证对于基于表单的用户和Azure AD用户都适用.现在,角色已在数据库中(使用OOTB Asp.net身份框架),并且已将角色作为对所有asp.net身份用户的声明获得.但是对于Azure AD身份用户,我无法获得角色声明.我尝试通过电子邮件查询数据库并获取Azure AD用户的角色,然后将其设置为角色声明,如下所示:

I have a webapp which supports both form based authentication (using OOTB Asp.net identity framework) and Azure AD based authentication (using OpenID Connect). the authentication works well for both forms based user and Azure AD users. Now the roles are in the database (using OOTB Asp.net identity framework) and the roles are obtained as claims for all the asp.net identity users. But for Azure AD identity users, i am not able to get the role claims. I tried querying the database with email and getting the roles for the Azure AD user and then setting it as the role claim as below:

User.SetClaims(ClaimTypes.Role,roleAdministrator.Name);//calling the set method

按如下所述设置声明.

 public static void SetClaims(this IPrincipal user,string claimType,string claimValue)
        {
            if (user?.Identity is ClaimsIdentity claimsIdentity)
            {
                var name = claimsIdentity.FindFirst(claimType);
                if (name != null)
                    claimsIdentity.RemoveClaim(name);
                claimsIdentity.AddClaim(new Claim(claimType, claimValue));
            }
        }

这仅适用于该特定的http请求,并且当我单击其他位置或刷新我的页面时,角色声明不再出现在Azure AD身份中.

This works only for that particular http request and as soon as I click somewhere else or refresh my page, the role claims are not present in the Azure AD identity anymore.

如何使用在asp.net身份角色(而不是作为Azure AD角色)中管理的角色来实现Azure AD身份验证

How can i implement Azure AD auth with roles managed in as asp.net identity roles (and not as Azure AD roles)

请注意,目前我不可以使用Azure AD角色,因为这是具有asp.net身份和角色的现有应用程序.我正在尝试以最少的更改添加一个身份验证提供程序.因此,角色必须像现在一样在数据库中.

推荐答案

如果要为Azure AD用户添加自定义属性,可以使用教程以注册扩展名,写入和读取扩展名值.

If we want to add custom attributes for Azure AD user, we could use Directory schema extensions, which can be used to add properties to directory objects without requiring an external data store. You could following this tutorial to register an extension, write and read an extension value.

如果可以使用Azure AD B2C,则可以

If Azure AD B2C is possible, you could define custom attributes in Azure Active Directory B2C.

关于如何获取自定义属性,请参阅另一种方法线程.

About how to get the custom attributes, please refer to another SO thread.

这篇关于将应用程序角色作为自定义声明添加到Azure AD身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆