ExamEdit&Check
This commit is contained in:
@@ -1,34 +1,51 @@
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.Extensions.DependencyInjection; // 需要这个命名空间来获取 IServiceProvider
|
||||
using System; // 需要这个命名空间来使用 Lazy<T>
|
||||
|
||||
namespace TechHelper.Client.HttpRepository
|
||||
{
|
||||
public class RefreshTokenService
|
||||
public class RefreshTokenService : IRefreshTokenService
|
||||
{
|
||||
private readonly AuthenticationStateProvider _authenticationStateProvider;
|
||||
private readonly IAuthenticationClientService _authenticationClientService;
|
||||
|
||||
public RefreshTokenService(AuthenticationStateProvider authenticationStateProvider, IAuthenticationClientService authenticationClientService)
|
||||
private readonly Lazy<AuthenticationStateProvider> _authenticationStateProvider;
|
||||
private readonly Lazy<IAuthenticationClientService> _authenticationClientService;
|
||||
|
||||
public RefreshTokenService(IServiceProvider serviceProvider)
|
||||
{
|
||||
_authenticationStateProvider = authenticationStateProvider;
|
||||
_authenticationClientService = authenticationClientService;
|
||||
_authenticationStateProvider = new Lazy<AuthenticationStateProvider>(
|
||||
() => serviceProvider.GetRequiredService<AuthenticationStateProvider>());
|
||||
|
||||
_authenticationClientService = new Lazy<IAuthenticationClientService>(
|
||||
() => serviceProvider.GetRequiredService<IAuthenticationClientService>());
|
||||
}
|
||||
|
||||
public async Task<string> TryRefreshToken()
|
||||
{
|
||||
var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
|
||||
var authState = await _authenticationStateProvider.Value.GetAuthenticationStateAsync();
|
||||
var user = authState.User;
|
||||
var expClaim = user.FindFirst(c => c.Type.Equals("exp")).Value;
|
||||
|
||||
// 如果 user 或 claims 为空,表示用户未认证,直接返回空字符串
|
||||
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.RefreshTokenAsync();
|
||||
return await _authenticationClientService.Value.RefreshTokenAsync(); // 访问 .Value 来调用方法
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user