【问题标题】:Getting ms graph api access token获取 ms graph api 访问令牌
【发布时间】:2020-09-25 08:01:17
【问题描述】:

我正在尝试为我的网络应用获取访问令牌。

据说文档会做这样的事情 MS Docs

所以我把我的代码写成这样......如果不正确请告诉我在哪里......

Dictionary<string, object> param_req_access_token = new Dictionary<string, object>();
        param_req_access_token["url"] = $@"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token";
        string str_basic_key = $"{client_id}:{client_secret}";
        byte[] encData_byte = new byte[str_basic_key.Length];
        encData_byte = System.Text.Encoding.UTF8.GetBytes(str_basic_key);
        string encodedData = Convert.ToBase64String(encData_byte);
        param_req_access_token["Headers"] = "Authorization: Bearer " + encodedData;
        param_req_access_token["ContentType"] = "application/x-www-form-urlencoded";
        StringBuilder postData_req_access_token = new StringBuilder();
        postData_req_access_token.Append($"client_id={client_id}");
        postData_req_access_token.Append($"&scope={HttpUtility.UrlEncode(scrope)}");
        postData_req_access_token.Append($"&code={code}");
        postData_req_access_token.Append($"&redirect_uri={HttpUtility.UrlEncode(redirect_uri)}");
        postData_req_access_token.Append($"&grant_type={grant_type}");
        postData_req_access_token.Append($"&client_secret={client_secret}");
        param_req_access_token["postData"] = postData_req_access_token.ToString();
        string responseData_req_access_token = RequestWebPage(param_req_access_token);

当然它不起作用...有什么解决方案吗?

【问题讨论】:

  • 您好,请参考我下面提供的解决方案。如果它对您的问题有帮助,请accept它作为答案(单击我的答案旁边的复选标记,将其从灰色切换为已填充)。先谢谢了~

标签: c# azure-active-directory microsoft-graph-api


【解决方案1】:

我不知道你在RequestWebPage做了什么,我只是写了一个示例来请求访问令牌供你参考:

using System;
using System.Collections.Generic;
using System.Net.Http;

namespace ConsoleApp2
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            HttpClient client = new HttpClient();

            var values = new Dictionary<string, string>
            {
                { "client_id", "09451791-883xxxxx" },
                { "scope", "openidxxxx" },
                { "code", "0.ARoATqvJ5Ce91UCEWSMLoxxxxx" },
                { "redirect_uri", "https://hurytest" },
                { "grant_type", "authorization_code" },
                { "client_secret", "aN9nerF4xxxxx" }
            };

            var content = new FormUrlEncodedContent(values);

            var response = await client.PostAsync("https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token", content);

            Console.WriteLine(response.Content.ReadAsStringAsync().Result);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    相关资源
    最近更新 更多