使用 Azure AD 在 Fiddler 中获取此请求的授权已被拒绝

Getting Authorization has been denied for this request in Fiddler with Azure AD

我创建了一个 ASP.Net Web API (.Net Framework) 应用程序,使用 "Work or School Accounts" 作为身份验证类型。这会自动在我的 Azure 订阅中注册这个 API 应用程序,我可以在 "App Registrations". I can see that Home Page Url is pointing to localhost address 下看到它。我可以看到 API 正在本地主机地址上本地启动。然后我启动 Fiddler 以从 Azure AD 获取访问令牌。我对端点 https://login.microsoftonline.com/<mytenant>.onmicrosoft.com/oauth2/token 的 POST 请求。具有以下 4 个参数

grant_type=client_credentials
&client_id=<appid from Azure AD Portal>
&client_secret=<secret from Azure AD Portal>
&resource=<appid from Azure AD Portal>

我得到了一个代币。当我解码此令牌时,我按预期看到 audappid(匹配 Azure AD 中的 appid)。我使用此令牌作为不记名令牌,通过在 https://localhost:44374/api/values 的 GET 请求中添加 Authorization: Bearer <mytoken> header 来调用 API 调用。但是,这个对我的 API 的 GET 调用返回 {"Message":"Authorization has been denied for this request."} 错误消息。

我错过了什么?

你应该使用App ID URI作为获取令牌时的resource值,你可以在Azure门户中的api应用程序的Properties中找到App ID URI ,比如 https://xxxxx.onmicrosoft.com/WebApplicationName 。 Web api 将检查访问令牌中的 aud 声明是否与您在 web.config 中设置的声明匹配:

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                    TokenValidationParameters = new TokenValidationParameters {
                         ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
                    },
                });

ida:Audience web.config 中的值是允许的观众。