Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. public class RevalidatingAuthenticationStateProvider : AuthenticationStateProvider, IDisposable
  2. {
  3. private static TimeSpan RefreshInterval = TimeSpan.FromMinutes(30);
  4.  
  5. private readonly CancellationTokenSource _cts;
  6. private ClaimsPrincipal _currentUser;
  7.  
  8. public RevalidatingAuthenticationStateProvider(SignInManager<IdentityUser> signInManager)
  9. {
  10. _cts = new CancellationTokenSource();
  11. _currentUser = signInManager.Context.User;
  12. _ = RefreshLoop(_cts.Token, signInManager);
  13. }
  14.  
  15. private async Task RefreshLoop(CancellationToken cancellationToken, SignInManager<IdentityUser> signInManager)
  16. {
  17. while (true)
  18. {
  19. await Task.Delay(RefreshInterval, cancellationToken);
  20. if (cancellationToken.IsCancellationRequested)
  21. {
  22. break;
  23. }
  24.  
  25. try
  26. {
  27. // Rebuild user data using latest info from Identity DB
  28. var identityUser = await signInManager.UserManager.GetUserAsync(_currentUser);
  29. _currentUser = await signInManager.CreateUserPrincipalAsync(identityUser);
  30. }
  31. catch
  32. {
  33. // If anything goes wrong, just log them out
  34. _currentUser = new ClaimsPrincipal();
  35. _cts.Cancel();
  36. }
  37.  
  38. NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
  39. }
  40. }
  41.  
  42. public override Task<AuthenticationState> GetAuthenticationStateAsync()
  43. => Task.FromResult(new AuthenticationState(_currentUser));
  44.  
  45. public void Dispose()
  46. => _cts.Cancel();
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement