AuthenticationResult does not contain refresh token

c# - Get refresh token additionally to access token with Microsoft.Identity.Client - Stack Overflow

MSAL.NET does not expose refresh tokens, for security reasons: MSAL handles refreshing tokens for you with token cache.

MSAL maintains a token cache and caches a token after it has been acquired. It's also capable of refreshing a token when it's getting close to expiration (as the token cache also contains a refresh token).

You can improve the availability of your application by regularly using WithForceRefresh which will internally acquire new access token when set to true

result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
             .WithForceRefresh(true)
             .ExecuteAsync();

Add access to refresh_token in Microsoft.Identity.Client.AuthenticationResult · Issue #1234 · AzureAD/microsoft-authentication-library-for-dotnet · GitHub

Does this documentation answer your question @mantasaudickas : https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/High-availability#pro-active-token-renewal ?

 

 

通过JwtSecurityToken里面的ValidTo和当前的时间比较,来判断是否需要重新请求token

private static string accessToken;

public static async Task<string> GetAccessTokenAsync()
{
    if (accessToken == null)
    {
        accessToken = await GetClientAccessTokenAsync();
    }
    else
    {
        var jwt = new JwtSecurityToken(accessToken);
        if (jwt.ValidTo <= DateTime.UtcNow.AddMinutes(5))
        {
            accessToken = await GetClientAccessTokenAsync();
        }
    }

    return accessToken;
}

public static async Task<string> GetClientAccessTokenAsync()
{
    var clientCredential = new ClientCredential(clientId, clientSecret);
    var authenticationContext = new AuthenticationContext(authority);
    var result = await authenticationContext.AcquireTokenAsync(resource, clientCredential);

    return result.AccessToken;
}

public static async Task<List<User>> GetUsersAsync()
{
    var accessToken = await GetAccessTokenAsync();

    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

    var response = await client.GetAsync($"https://graph.microsoft.com/v1.0/users?$select=id,displayName,mail,userPrincipalName");

    var content = await response.Content.ReadAsStringAsync();
    var users = JsonConvert.DeserializeObject<GraphApiResponse<User>>(content);

    return users.Value;
}

 

token超时之后的提示是,

{
    "error": {
        "code": "InvalidAuthenticationToken",
        "message": "Access token has expired or is not yet valid.",
        "innerError": {
            "date": "2023-03-31T03:28:18",
            "request-id": "3ac0d9ae-7",
            "client-request-id": "3ac0d9ae-74"
        }
    }
}
 
 
 
 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2022-03-28 炉石传说 佣兵战纪 装备
2022-03-28 What can be the reasons of connection refused errors?
2022-03-28 Big Data & Cloud Computing: The Roles & Relationships
2020-03-28 Why can two different enum enumeration-constants have the same integer value?
2019-03-28 Singleton Pattern单例模式
2016-03-28 T4 Templates and the Entity Framework
2016-03-28 Entity Framework Utility .ttinclude File
点击右上角即可分享
微信分享提示