好的,我为此苦苦挣扎了一段时间,我相信我已经弄清楚了。
首先,
在 Azure AD 中,将您的 WebApi 应用程序设置为应用程序类型为 Web 应用程序/API。
转到清单文件并添加您的角色,例如
[
{
"allowedMemberTypes": [
"User"
],
"displayName": "Reviewer",
"id": "0238c2bb-9857-4d07-b760-a47ec621d57a",
"isEnabled": true,
"description": "Reviewer only have the ability to view tasks and their statuses.",
"value": "reviewer"
},
{
"allowedMemberTypes": [
"User"
],
"displayName": "Approver",
"id": "000018cb-19e3-4f89-bf99-5d7acf30773b",
"isEnabled": true,
"description": "Approvers have the ability to change the status of tasks.",
"value": "approver"
}
]
然后将 Client 应用程序创建为 Application 类型为 Native 应用程序,并为您在上面添加的服务添加所需的权限。
在 SPA Angular 应用程序中添加类似这样的内容
var endPoints = {
// "https://localhost:44386/" is the API URL
// "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" is the Service Application ID
"https://localhost:44386/": "xxxxxxxxxxxxxxxxxxxxxxxxxx"
};
adalAuthenticationServiceProvider.init({
instance: "https://login.microsoftonline.com/",
// tenant is your tenant name (something like below)
tenant: "{NAME}.onmicrosoft.com",
// this is the Native app application ID (ClientID) you registered
clientId: "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
extraQueryParameter: "nux=1",
endpoints: endPoints
}, $httpProvider);
}
]);
然后,您需要在您的 startup.cs 中设置 Service App,如下所示:
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters
{
/* "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" is the Service Application ID. (Same as you registered in the client app above)*/
ValidAudience = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
RoleClaimType = "roles"
},
/*enant is your tenant name (same as you registered in client app above)*/
Tenant = "{NAME}.onmicrosoft.com"
});
最后,您需要转到 Azure 活动目录 => 企业应用程序 => 所有应用程序 => 选择您的 webAPI 服务 => 用户和组 => 然后将用户分配给角色。
当您通过客户端应用程序登录以进行身份验证并调用 webapi 时,这一切都完成后,adal.js 和 ada-angular.js 将放置包含角色的正确不记名令牌