Forked from SteveSandersonMS/RevalidatingAuthenticationStateProvider.cs
Created
February 3, 2023 12:55
-
-
Save benjaminvanrenterghem/46cb42286425bdce570853b85abf075d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RevalidatingAuthenticationStateProvider : AuthenticationStateProvider, IDisposable | |
{ | |
private static TimeSpan RefreshInterval = TimeSpan.FromMinutes(30); | |
private readonly CancellationTokenSource _cts; | |
private ClaimsPrincipal _currentUser; | |
public RevalidatingAuthenticationStateProvider(SignInManager<IdentityUser> signInManager) | |
{ | |
_cts = new CancellationTokenSource(); | |
_currentUser = signInManager.Context.User; | |
_ = RefreshLoop(_cts.Token, signInManager); | |
} | |
private async Task RefreshLoop(CancellationToken cancellationToken, SignInManager<IdentityUser> signInManager) | |
{ | |
while (true) | |
{ | |
await Task.Delay(RefreshInterval, cancellationToken); | |
if (cancellationToken.IsCancellationRequested) | |
{ | |
break; | |
} | |
try | |
{ | |
// Rebuild user data using latest info from Identity DB | |
var identityUser = await signInManager.UserManager.GetUserAsync(_currentUser); | |
_currentUser = await signInManager.CreateUserPrincipalAsync(identityUser); | |
} | |
catch | |
{ | |
// If anything goes wrong, just log them out | |
_currentUser = new ClaimsPrincipal(); | |
_cts.Cancel(); | |
} | |
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); | |
} | |
} | |
public override Task<AuthenticationState> GetAuthenticationStateAsync() | |
=> Task.FromResult(new AuthenticationState(_currentUser)); | |
public void Dispose() | |
=> _cts.Cancel(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment