如何将Daemon或Server的Azure AD OAuth2访问令牌和刷新令牌转换为C#ASP.NET Web API

Jul*_*lla 4 c# security azure oauth-2.0 azure-active-directory

我已经将Azure AD OAuth2守护程序或服务器实现为ASP.NET Web API.但是我只收到一个访问令牌,它是AuthenticationResult上的属性.见下面的实施.

    public IHttpActionResult GetAccessToken(string clientId, string clientkey)
    {
        AuthenticationContext authContext = new AuthenticationContext(authority);
        ClientCredential clientCredential = new ClientCredential(clientId, clientkey);
        AuthenticationResult authenticationResult = authContext.AcquireTokenAsync(resourceUri, clientCredential).Result;
        Authorisation authorisation = new Authorisation {access_token = authenticationResult.AccessToken,
                                                token_type = authenticationResult.AccessTokenType,
                                                expires_on = authenticationResult.ExpiresOn };

        return Ok(authorisation);
    }   
Run Code Online (Sandbox Code Playgroud)

这仅返回访问令牌.我想要一个实现,一个守护进程或服务器实现,它返回访问令牌和刷新令牌.有你看过或做过类似的实现.欢迎任何有用的示例链接.

Jul*_*lla 6

当我发布这个问题时,这是我正在寻找的答案,请参阅下面的屏幕截图以获得预期结果和c#控制台解决方案.找到解决方案后,值得在这里分享,有朝一日可能对某人有用

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Postman的屏幕截图 - 预期结果.除了不太可读之外,您将在控制台中获得相同的结果

在此输入图像描述