-
-
Save explorer14/80607b5622cf1978bf06352ed8bf418b 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 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