ExamEdit&Check
This commit is contained in:
46
TechHelper.Client/HttpRepository/RefreshTokenService2.cs
Normal file
46
TechHelper.Client/HttpRepository/RefreshTokenService2.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user