我正在尝试使用以下内容来确定Azure AD B2C登录用户是否为管理员:
if (User.IsInRole("Administrator"))
{
.... Display special info for Admins ....
}
但是,当我查看System.Security.Principal.IPrincipal.User
对象时,我会看到null
以获取该用户拥有的角色列表:
以下是配置身份验证和请求TokenValidationParameters
的相关代码,包括要验证的角色。我尝试了以下内容:RoleClaimType = "role"
和RoleClaimType = "roles"
,这两个都没有为我效用。
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseKentorOwinCookieSaver();
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieSecure = CookieSecureOption.Always
});
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// Generate the metadata address using the tenant and policy information
MetadataAddress = String.Format(AadInstance, Tenant, DefaultPolicy),
// These are standard OpenID Connect parameters, with values pulled from web.config
ClientId = ClientId,
Authority = Authority,
PostLogoutRedirectUri = RedirectUri,
RedirectUri = RedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
RedirectToIdentityProvider = OnRedirectToIdentityProvider,
AuthenticationFailed = OnAuthenticationFailed,
AuthorizationCodeReceived = OnAuthorizationCodeReceived
},
/////////// HERE //////////
// Specify the claims to validate
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role",
},
// Specify the scope by appending all of the scopes requested into one string (seperated by a blank space)
Scope = $"{OpenIdConnectScopes.OpenId} {ReadTasksScope} {WriteTasksScope}"
}
);
}
但是,当我解码从身份验证过程中检索到的id_token
并使用工具https://jwt.ms/对其进行解码时,我没有看到“角色”声明,如屏幕截图所示。
此外,在SignIn Azure AD B2C策略中,我是否需要添加“角色”ClaimType?
请帮忙!为了让User.IsInRole("Administrator")
工作,我还需要做些什么?谢谢!
答案 0 :(得分:0)
为解决此问题,我最终使用Azure AD Graph Client查询属于具有指定objectId
的用户的所有目录角色。这是我添加的方法:
public async Task<string> GetUserRoleByObjectId(string objectId)
{
return await SendGraphGetRequest("/users/" + objectId + "/$links/memberOf", null);
}
我将此方法添加到以下示例代码中的B2CGraphClient.cs
文件中,该文件已整合到我的网络应用中:https://github.com/AzureADQuickStarts/B2C-GraphAPI-DotNet