微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我已经将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);
    }   

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

解决方法:

当我发布这个问题时,这是我正在寻找的答案,请参阅下面的屏幕截图以获得预期结果和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. [email protected]>"),
                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();
        }
    }
}

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

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐