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

标签 c# asp.net azure

我在 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/

相关文章:

c# - 微软统一。如何在构造函数中指定某个参数?

c# - 报告 (RDLC) 本地化/全局化

azure - ReadDocumentAsync 的 CancellationToken

Azure数据工厂复制管道: get a file with date of yesterday that arrived today

c# - ASP.net MVC 5 Razor 下拉框

azure - JSON 对象作为 ARM 模板函数参数

c# - 如何旋转矩形C#中的文本

c# - Withings API 和 C#

c# - 如何从 VS 2012 创建 XBAP

c# - 基于 Empty XML 示例合并丢失的 XML 记录