Files
TechHelper/TechHelper.Client/HttpRepository/RefreshTokenService2.cs
2025-06-12 19:01:05 +08:00

47 lines
1.3 KiB
C#

using Microsoft.AspNetCore.Components.Authorization;
namespace TechHelper.Client.HttpRepository
{
public class RefreshTokenService2
{
private readonly Lazy<AuthenticationStateProvider> _authenticationStateProvider;
private readonly Lazy<IAuthenticationClientService> _authenticationClientService;
public RefreshTokenService2(IServiceProvider serviceProvider)
{
_authenticationStateProvider = new Lazy<AuthenticationStateProvider>(
() => serviceProvider.GetRequiredService<AuthenticationStateProvider>());
_authenticationClientService = new Lazy<IAuthenticationClientService>(
() => serviceProvider.GetRequiredService<IAuthenticationClientService>());
}
public async Task<string> TryRefreshToken()
{
var authState = await _authenticationStateProvider.Value.GetAuthenticationStateAsync();
var user = authState.User;
if (user?.Identity == null || !user.Identity.IsAuthenticated)
{
return string.Empty;
}
var expClaim = user.FindFirst(c => c.Type.Equals("exp"))?.Value;
if (string.IsNullOrEmpty(expClaim))
{
return string.Empty;
}
var expTime = DateTimeOffset.FromUnixTimeSeconds(
Convert.ToInt64(expClaim));
var diff = expTime - DateTime.UtcNow;
if (diff.TotalMinutes <= 2)
return await _authenticationClientService.Value.RefreshTokenAsync();
return string.Empty;
}
}
}