Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save benjaminvanrenterghem/46cb42286425bdce570853b85abf075d to your computer and use it in GitHub Desktop.
Save benjaminvanrenterghem/46cb42286425bdce570853b85abf075d to your computer and use it in GitHub Desktop.
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