我正在尝试通过 Azure 中的应用注册来控制授权。
现在,我设置了两个应用注册。
- 应用程序
- 客户端应用程序
ApiApp 使用默认设置进行设置,但我已将其添加到清单中:
"oauth2Permissions": [
{
"adminConsentDescription": "Allow admin access to ApiApp",
"adminConsentDisplayName": "Admin",
"id": "<guid>",
"isEnabled": true,
"type": "User",
"userConsentDescription": "Allow admin access to ApiApp",
"userConsentDisplayName": "Admin",
"value": "Admin"
},
...
]
在客户端应用程序注册中,我拥有所有默认值,但我添加了:
- 在密钥中,用于针对 AD 验证应用程序的密码
- 在所需权限中,我添加了 ApiApp 并需要委派权限“管理员”。我保存了它,单击完成,然后单击“授予权限”以确保权限已强制更新。
在我的客户端应用程序中,它使用此代码进行身份验证:
...
var context = new AuthenticationContext(authority);
var clientCredentials = new ClientCredential(<clientId>, <clientSecret>);
var result = await context.AcquireTokenAsync(<apiAppUri>, clientCredentials);
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
var webResult = await client.GetAsync(<api uri>);
如果您在创建 Web API 项目时选择工作或学校帐户,我的 ApiApp 只是使用内置授权:
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters {
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
},
});
}
这有效:
[Authorize]
public class ValuesController : ApiController
这些不起作用:
[Authorize(Users = "Admin")]
public class ValuesController : ApiController
或者
[Authorize(Roles= "Admin")]
public class ValuesController : ApiController
根据我正在阅读的内容,我相信除了 ApiApp 项目本身之外,我已经正确设置了所有内容。我认为我需要以不同方式或使用额外信息设置授权,以允许 oauth2Permission 范围正确用于 WebAPI。
我缺少哪些步骤来允许 WebAPI 中的特定范围而不仅仅是 [Authorize] 属性?
我使用Integrating applications with Azure Active Directory来帮助我设置应用程序注册,以及使用客户端凭据服务调用的服务,但我似乎无法准确找到在 Web API 部分中实现代码所需的内容。
更新
我找到了这个资源:Azure AD .NET Web API 入门
它表明您可以使用此代码检查范围声明:
public IEnumerable<TodoItem> Get()
{
// user_impersonation is the default permission exposed by applications in Azure AD
if (ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope")
.Value != "user_impersonation")
{
throw new HttpResponseException(new HttpResponseMessage {
StatusCode = HttpStatusCode.Unauthorized,
ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found"
});
}
...
}
但是,我得到的权利要求不包括任何范围权利要求。