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 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 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> 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>(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"

        }

    }

}

 

 

 

 

 

推荐链接

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。