gpt4 book ai didi

c# - 如何刷新通过 Azure 身份验证收到的访问 token ?

转载 作者:行者123 更新时间:2023-12-03 06:33:04 27 4
gpt4 key购买 nike

我在 Azure 服务应用程序中有一段常见的(类似教程的)代码。 HomeController 初始化为:

public HomeController(ILogger<HomeController> logger, GraphServiceClient graphServiceClient, ITokenAcquisition tokenAcquisition)
{
var task = Task.Run(async () => await m_tokenAcquisition.GetAuthenticationResultForUserAsync(new[] { "some.allowed.scope" }));
var context = task.Result;
var accessToken = context.AccessToken;
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestHeaders.Add("FeatureFlag", "00000004");
var newGraphClient = new GraphServiceClient(client);
}

访问 token 非常适合“GraphServiceClient”。

访问 token 在一个小时左右过期后将无法使用。但该服务需要在 Azure 帐户上定期执行工作,而不打扰用户。

主要问题是如何防止用户频繁登录?

最佳答案

To access the refreshed token without asking users to login.

您需要自定义代码,以便通过计时器在应用程序中刷新 token ,方法是在 token 过期之前检查 token 过期情况,或者添加 token 过期事件的监听器。

_timer = new Timer(TokenRefresh, null, _expiresIn * 1000 - 60000, Timeout.Infinite);


using (var client = new HttpClient())
{
var response = await client.PostAsync("https://authserver.com/token", new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grantType", "tokenRefresh"),
new KeyValuePair<string, string>("tokenRefresh", _tokenRefresh)
}));
var responseContent = await response.Content.ReadAsStringAsync();

var json = JObject.Parse(responseContent);
_accessToken = (string)json["accessToken"];
_tokenRefresh = (string)json["tokenRefresh"];
_expiresIn = (int)json["expiresIn"];
//Expires in 1 hrs (3600)
}

_timer.Change(_expiresIn * 1000 - 60000, Timeout.Infinite);

您需要登录该应用程序。

应用程序必须将登录凭据发送到身份验证服务器并验证它们。然后返回访问 token 、刷新 token 。现在您在客户端安全地拥有了访问 token 和刷新 token 。

当访问 token 过期时,应用程序使用刷新 token 向身份验证服务器请求新的访问 token 。身份验证服务器检查刷新 token 并返回新的访问 token 。

您需要自定义代码,以便通过计时器在应用程序中刷新 token ,方法是在 token 过期之前检查 token 过期情况,或者添加 token 过期事件或委托(delegate)的监听器

由于刷新 token 的生命周期很短,您需要使用 token 刷新过程中获得的新刷新 token 再次获取新的访问 token 。

为了安全起见,刷新 token 和访问 token 必须安全存储并加密。

引用资料来自

Token Requests

Github Code

关于c# - 如何刷新通过 Azure 身份验证收到的访问 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75132054/

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