c# - 如何为我的 Azure 应用程序创建应用程序 token ?

标签 c# asp.net azure api azure-devops

因此,我尝试从我的 Azure 应用程序中存在的“OAuth 2.0 token 端点 (v2)”端点获取 token 。就是这样。

[HttpGet("GetApplicationToken")]
public async Task<ActionResult> GetApplicationToken()
{
      HttpClient client = new HttpClient();
      var url = "https://login.microsoftonline.com/680ea9b1-xxxx-xxxx-xxxx-xxxxxxxxxxxx/oauth2/v2.0/token";

      var parameters = new Dictionary<string, string>
      {
          {"client_id", "41d391ef-xxxx-xxxx-xxxx-xxxxxxxxxxxx" },
          {"scope", "api://41d391ef-xxxx-xxxx-xxxx-xxxxxxxxxxxx/access_as_user" },
          {"client_secret", "PXa8Q~xx" },
          {"grant_type", "client_credentials" }
      };
      var encodedContent = new FormUrlEncodedContent(parameters);

      var response = await client.PostAsync(url, encodedContent);

      if (response.IsSuccessStatusCode)
      {
          var responseStr = await response.Content.ReadAsStringAsync();
          return Ok(JsonConvert.DeserializeObject<TokenResponse>(responseStr));
      }

      return StatusCode(500);

我得到的输出是:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.6.1","title":"An error occurred while processing your request.","status":500,"traceId":"00-d0da4fd71ec21cb0f8b364e3853bda37-ed1dcd82609eef73-00"}

我希望它返回一个我的 api 可以使用的应用程序 token ,但我不知道问题可能是什么。 谢谢!

最佳答案

使用客户端凭据流程时,范围参数应为“api://41d391ef-xxxx-xxxx-xxxx-xxxxxxxxxxxx/.default”。 这是因为您只能在应用注册中使用静态定义的权限,这与涉及用户的身份验证流程不同,身份验证流程可以动态使用范围。

文档:https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow#first-case-access-token-request-with-a-shared-secret .

引用有关范围参数的文档:

The value passed for the scope parameter in this request should be the resource identifier (application ID URI) of the resource you want, affixed with the .default suffix.

(除了应用程序 ID URI 之外,它也可以是客户端/应用程序 ID)

此外,无论状态码是否成功,都最好读取响应内容,这样您就可以检查返回的错误。 此外,使用 MSAL 会更容易为此,无需手动调用 API。

关于c# - 如何为我的 Azure 应用程序创建应用程序 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75885711/

相关文章:

c# - SlimDX DirectInput 初始化

c# - CSS 颜色被链接覆盖

c# - Ninject - Binding.GetProvider 抛出 NullReferenceException

python - 批量插入到 Azure SQL 且 SQLAlchemy 不持久

c# - 从 Azure 应用程序配置动态更新 .net core 配置

c# - 如何在运行时根据现有数据模型中的数据构建自定义的动态 ViewModel?

asp.net - 有什么方法可以过滤 IIS 提供的页面中的某些内容吗?

c# - 通过反射查找asp.net webform方法

python - Azure B2C : Error in the callback after the edit profile when it tries to get a new token

azure - Microsoft Graph API - 使用哪种授权类型直接获取 AccessToken,无需任何用户干预