如何正确请求 Azure 不记名令牌或为什么它要求我发送 "scope" 参数?

How to request an Azure bearer token properly or why does it ask me to send a "scope" parameter?

情况:

我有一个 WPF 应用程序,它必须调用通过 Azure Active Directory 保护的 http 触发器函数。在尝试检索不记名令牌以进行进一步调用时,我得到以下响应(无论我是通过邮递员还是通过代码进行):

AADSTS90014: The required field 'scope' is missing

我做了什么:

我阅读了大量不同的文章和博客文章,解释如何使用 Azure AD 保护 http 触发功能并通过休息请求检索不记名令牌。在其中一篇我认为最适合我需要的文章之后,我创建了 azure 函数应用程序、azure 函数、azure AD 配置和应用程序注册的完整设置。

在那之后,我只想通过发送不记名令牌和一些其他参数来使用 azure 函数并获得结果,但我在检索不记名令牌时遇到了困难。

代码(以防万一):

var restClient = new RestClient("https://login.microsoftonline.com/{myTenant}/oauth2/v2.0/token");
var restRequest = new RestRequest(Method.POST);
restRequest.AddHeader("content-type", "application/x-www-form-urlencoded");
restRequest.AddParameter("grant_type", "client_credentials", ParameterType.GetOrPost);
restRequest.AddParameter("client_id", "{app id from azure ad app}", ParameterType.GetOrPost);
restRequest.AddParameter("client_secret", "{generated secret}", ParameterType.GetOrPost);
restRequest.AddParameter("ressource", "https://{somefunctionname}.azurewebsites.net", ParameterType.GetOrPost);
var restResponse = restClient.Execute(restRequest);

Postman 正文参数(x-www-form-urlencoded):

grant_type = "client_credentials"

client_id = {app id from azure ad app}

client_secret = {generated secret}

ressource = "https://somefunctionname.azurewebsites.net"

和我用来获取令牌的Url:

https://login.microsoftonline.com/{myTenant}/oauth2/v2.0/token

我的问题:

所以在详细了解情况后,我有两个主要问题:

  1. 为什么在我的情况下身份验证服务需要一个 "scope" 参数(我的设置或休息请求是否有问题)?
  2. 万一我必须发送一个值,要发送哪个范围值?

根据你提供的信息,我认为你想使用Azure AD v2.0 to access the function protected by Azure AD. If so, since you use Azure AD v2.0, you need to update resource to scope. And the vaule of scope should be ```{app id URI}/.default. For more details, please refer to OAuth 2.0 client credentials flow

关于如何获取访问令牌,请参考以下步骤。

  1. 注册客户端访问网络api

    一个。注册一个新的 Azure AD 应用程序

    b。配置权限

    c。创建一个新的秘密

    d。获取应用程序 ID url

  2. 代码

 var client = new RestClient("https://login.microsoftonline.com/<your tenant>/oauth2/v2.0/token");
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("grant_type", "client_credentials", ParameterType.GetOrPost);
            request.AddParameter("client_id", "your app id", ParameterType.GetOrPost);
            request.AddParameter("client_secret", "your app secret", ParameterType.GetOrPost);
            request.AddParameter("scope", "<your app id url>/.default", ParameterType.GetOrPost);
            IRestResponse response = client.Execute(request);

结果:

正如上面提到的针对 azure AD v2 的答案,您不会获得针对资源的令牌,而是针对范围的令牌。要么将您的权限更改为 https://login.microsoftonline.com/{myTenant}/oauth2/token 然后您可以使用 v1 端点并获取针对您的资源的令牌

否则您要么使用上述答案中提到的默认范围,要么您可以转到 Azure 门户并转到应用程序注册页面并导航到公开 API 部分,然后检查是否有范围已经存在你可以使用它,如果没有创建一个

还要确保 https://{somefunctionname}.azurewebsites.net 是您的应用程序 ID URI