Skip to content

Instantly share code, notes, and snippets.

@explorer14
Last active January 12, 2021 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save explorer14/80607b5622cf1978bf06352ed8bf418b to your computer and use it in GitHub Desktop.
Save explorer14/80607b5622cf1978bf06352ed8bf418b to your computer and use it in GitHub Desktop.
public class MyAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly IAuthenticationService authService;
private readonly IClientTokenStorage clientTokenStorage;
private AuthenticationState currentAuthenticationState;
public MyAuthenticationStateProvider(
IAuthenticationService authService,
IClientTokenStorage clientTokenStorage)
{
this.authService = authService;
this.clientTokenStorage = clientTokenStorage;
this.authService.UserLoggedIn = async () =>
{
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
};
this.authService.UserLoggedOut = async () =>
{
await this.clientTokenStorage.RemoveToken(AuthConstants.AUTH_TOKEN_KEY);
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
};
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
var authToken = await clientTokenStorage.GetToken(
AuthConstants.AUTH_TOKEN_KEY);
if (string.IsNullOrWhiteSpace(authToken) ||
HasTokenExpired(authToken))
{
await clientTokenStorage.RemoveToken(AuthConstants.AUTH_TOKEN_KEY);
currentAuthenticationState = new AuthenticationState(
new ClaimsPrincipal(
new ClaimsIdentity()));
}
else
{
currentAuthenticationState = new AuthenticationState(
new ClaimsPrincipal(
new ClaimsIdentity(
JwtClaimsParser.GetClaims(authToken),
"password")));
}
return currentAuthenticationState;
}
private bool HasTokenExpired(string authToken)
{
var claims = JwtClaimsParser.GetClaims(authToken);
var expiryClaim = claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Exp);
var expiresOn = long.Parse(expiryClaim.Value);
return DateTimeOffset.UtcNow.ToUnixTimeSeconds() > expiresOn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment