1
0
mirror of https://github.com/chylex/Minecraft-Phantom-Panel.git synced 2024-11-22 08:42:44 +01:00
Minecraft-Phantom-Panel/Server/Phantom.Server.Web.Identity/Authentication/RevalidatingIdentityAuthenticationStateProvider.cs

53 lines
2.0 KiB
C#

using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Phantom.Server.Web.Identity.Authentication;
sealed class RevalidatingIdentityAuthenticationStateProvider<TUser> : RevalidatingServerAuthenticationStateProvider where TUser : class {
private readonly IServiceScopeFactory scopeFactory;
private readonly IdentityOptions options;
public RevalidatingIdentityAuthenticationStateProvider(ILoggerFactory loggerFactory, IServiceScopeFactory scopeFactory, IOptions<IdentityOptions> optionsAccessor) : base(loggerFactory) {
this.scopeFactory = scopeFactory;
this.options = optionsAccessor.Value;
}
protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30);
protected override async Task<bool> ValidateAuthenticationStateAsync(AuthenticationState authenticationState, CancellationToken cancellationToken) {
// Get the user manager from a new scope to ensure it fetches fresh data
var scope = scopeFactory.CreateScope();
try {
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<TUser>>();
return await ValidateSecurityStampAsync(userManager, authenticationState.User);
} finally {
if (scope is IAsyncDisposable asyncDisposable) {
await asyncDisposable.DisposeAsync();
}
else {
scope.Dispose();
}
}
}
private async Task<bool> ValidateSecurityStampAsync(UserManager<TUser> userManager, ClaimsPrincipal principal) {
var user = await userManager.GetUserAsync(principal);
if (user == null) {
return false;
}
else if (!userManager.SupportsUserSecurityStamp) {
return true;
}
else {
var principalStamp = principal.FindFirstValue(options.ClaimsIdentity.SecurityStampClaimType);
var userStamp = await userManager.GetSecurityStampAsync(user);
return principalStamp == userStamp;
}
}
}