RevalidatingIdentityAuthenticationStateProvider.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using Microsoft.AspNetCore.Components;
  2. using Microsoft.AspNetCore.Components.Authorization;
  3. using Microsoft.AspNetCore.Components.Server;
  4. using Microsoft.AspNetCore.Identity;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using Microsoft.Extensions.Options;
  8. using System;
  9. using System.Security.Claims;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace HyperCube.Areas.Identity
  13. {
  14. public class RevalidatingIdentityAuthenticationStateProvider<TUser>
  15. : RevalidatingServerAuthenticationStateProvider where TUser : class
  16. {
  17. private readonly IServiceScopeFactory _scopeFactory;
  18. private readonly IdentityOptions _options;
  19. public RevalidatingIdentityAuthenticationStateProvider(
  20. ILoggerFactory loggerFactory,
  21. IServiceScopeFactory scopeFactory,
  22. IOptions<IdentityOptions> optionsAccessor)
  23. : base(loggerFactory)
  24. {
  25. _scopeFactory = scopeFactory;
  26. _options = optionsAccessor.Value;
  27. }
  28. protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30);
  29. protected override async Task<bool> ValidateAuthenticationStateAsync(
  30. AuthenticationState authenticationState, CancellationToken cancellationToken)
  31. {
  32. // Get the user manager from a new scope to ensure it fetches fresh data
  33. var scope = _scopeFactory.CreateScope();
  34. try
  35. {
  36. var userManager = scope.ServiceProvider.GetRequiredService<UserManager<TUser>>();
  37. return await ValidateSecurityStampAsync(userManager, authenticationState.User);
  38. }
  39. finally
  40. {
  41. if (scope is IAsyncDisposable asyncDisposable)
  42. {
  43. await asyncDisposable.DisposeAsync();
  44. }
  45. else
  46. {
  47. scope.Dispose();
  48. }
  49. }
  50. }
  51. private async Task<bool> ValidateSecurityStampAsync(UserManager<TUser> userManager, ClaimsPrincipal principal)
  52. {
  53. var user = await userManager.GetUserAsync(principal);
  54. if (user == null)
  55. {
  56. return false;
  57. }
  58. else if (!userManager.SupportsUserSecurityStamp)
  59. {
  60. return true;
  61. }
  62. else
  63. {
  64. var principalStamp = principal.FindFirstValue(_options.ClaimsIdentity.SecurityStampClaimType);
  65. var userStamp = await userManager.GetSecurityStampAsync(user);
  66. return principalStamp == userStamp;
  67. }
  68. }
  69. }
  70. }