gpt4 book ai didi

c# - 如何获取守护程序或服务器到 C# ASP.NET Web API 的 Azure AD OAuth2 访问 token 和刷新 token

转载 作者:太空狗 更新时间:2023-10-30 00:29:58 27 4
gpt4 key购买 nike

我已经实现了 Azure AD OAuth2 守护程序或服务器到 ASP.NET Web API。但是我只收到一个访问 token ,它是 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);
}

这仅返回访问 token 。我想要一个实现,一个返回访问 token 和刷新 token 的守护进程或服务器实现。您是否见过或做过类似的实现。欢迎任何有用的示例链接。

最佳答案

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

C# 控制台应用代码可在下面的 postman 屏幕截图中实现预期结果

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. <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472d322b2e323469232237322b2b2607223f262a372b226924282a" rel="noreferrer noopener nofollow">[email protected]</a>>"),
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

关于c# - 如何获取守护程序或服务器到 C# ASP.NET Web API 的 Azure AD OAuth2 访问 token 和刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44161892/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com