且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取Daemon或Server的Azure AD OAuth2访问令牌和刷新令牌到C#ASP.NET Web API

更新时间:2023-02-14 23:37:24

当我发布此问题时,这就是我正在寻找的答案,请参见下面的屏幕快照,以获取预期的结果和c#控制台解决方案.找到解决方案后,值得在这里分享它,有一天可能对某人有用

When I posted this question, this was the answer I was looking for, please see screen shot below for expected result and c# console solution. Having found the solution, it is worth sharing it here, may be useful to someone some day

C#控制台应用程序代码可在下面的邮递员屏幕截图中获得预期的结果

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

namespace AzureADTokenApp
{
    class Program
    {
        static void Main(string[] args)
        {

            var client = new HttpClient();
            var uri = "https://login.microsoftonline.com/<tenant-name>.onmicrosoft.com/oauth2/token?api-version=1.0";
            var pairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("resource", "https://graph.microsoft.com"),
                new KeyValuePair<string, string>("client_id", "<azure ad client id e.g. 9b864-a5e6-4f0d-b155-1f53a6c78>"),
                new KeyValuePair<string, string>("client_secret", "<azure ad client secret e.g. MTMiXaO1P9HnhSawdXWmcnuQ="),
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", "<azure ad user e.g. julius.depulla@example.com>"),
                new KeyValuePair<string, string>("password", "<azure ad user password e.g. Pa$$word01>"),
                new KeyValuePair<string, string>("scope", "openid")
             };

            var content = new FormUrlEncodedContent(pairs);

            var response = client.PostAsync(uri, content).Result;

            string result = string.Empty;

            if (response.IsSuccessStatusCode)
            {

                result = response.Content.ReadAsStringAsync().Result;
            }

            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

邮递员截屏-预期结果.您将在控制台中获得相同的结果,但可读性较差