【问题标题】:How to generate Bearer Token using C# REST API Authenticate with Bearer Token?如何使用 C# REST API 使用承载令牌进行身份验证生成承载令牌?
【发布时间】:2018-01-15 12:23:35
【问题描述】:

我正在尝试创建 webjob 来执行 Token 端点并生成承载令牌并执行 Graph End Point 来查询图?如何使用 C# REST Api 实现相同的目标?什么是令牌端点?以下是 Postman 工具中生成的令牌的屏幕截图。

【问题讨论】:

    标签: azure azure-cosmosdb azure-webjobs


    【解决方案1】:

    什么是令牌端点?

    https://login.windows.net/<tenant-id>/oauth2/token
    

    如何使用 C# REST Api 实现相同的目标?

    如果你想在 Azure AD OAuth 中使用 Resource Owner Password Credentials Grant,你可以从这个blog 得到答案。以下是博客中的sn-p。

    注意:

    1. 此外,请注意资源所有者密码授予不提供同意,并且也不支持 MFA
    2. 请使用 native Azure AD application 进行测试。
    3. 将用户添加为应用程序所有者

    以下是 Azure AD OAuth 中资源所有者所需的参数

    密码授予。

    名字

    说明

    grant_type - OAuth 2 授权类型:密码

    resource - 使用令牌的应用,例如 Microsoft Graph、Azure AD Graph 或您自己的 Restful 服务

    client_id - Azure AD 中已注册应用程序的客户端 ID

    用户名 - Azure AD 中的用户帐户

    password - 用户帐号的密码

    scope - 可选,如openid获取Id Tok

    演示代码:

    using (HttpClient client = new HttpClient())
    {
      var tokenEndpoint = @"https://login.windows.net/<tenant-id>/oauth2/token";
      var accept = "application/json";
    
      client.DefaultRequestHeaders.Add("Accept", accept);
      string postBody = @"resource=https%3A%2F%2Fgraph.microsoft.com%2F
      &client_id=<client id>
      &grant_type=password
      &username=xxx@xxx.onmicrosoft.com
      &password=<password>
      &scope=openid";
    
      using (var response = await client.PostAsync(tokenEndpoint, new StringContent(postBody, Encoding.UTF8, "application/x-www-form-urlencoded")))
      {
        if (response.IsSuccessStatusCode)
        {
          var jsonresult = JObject.Parse(await response.Content.ReadAsStringAsync());
          token = (string)jsonresult["access_token"];
        }
      }
    }
    

    更新:

    根据你的评论,我也用RestClient做了一个demo。

    var tenantId = "xxxxxx";
    var client = new RestClient("https://login.windows.net/");
    var request = new RestRequest($"{tenantId}/oauth2/token", Method.POST);
    //// easily add HTTP Headers
    request.AddHeader("Accept", "application/json");
    string postBody = @"resource=https://graph.microsoft.com/&client_id=xxxxx&grant_type=password&username=xxxxx&password=xxxxx&scope=openid";
    request.AddParameter("application/x-www-form-urlencoded", postBody, ParameterType.RequestBody); //add request text body 
    IRestResponse response = client.Execute(request);
    var content = response.Content;
    var token = JObject.Parse(content)["access_token"];
    

    测试结果:

    【讨论】:

    • 我要使用 REST 客户端
    • 感谢回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 2022-01-23
    • 2017-02-24
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    相关资源
    最近更新 更多