Auth0, angular 2 documentation, advices to check authentication this way
get authenticated(){
return tokenNotExpired("token");
}
However if I have a thousand place in my views where I check for authentication I don’t want my app to decode the token a thousand times. I’d prefer to set a flag on authetication and refresh the token when needed (read comments)
isAuthenticated: boolean = false;
// called on startup
init(){
// authenticates
this.auth0.parseHash({ _idTokenVerification: false }, (err, authResult) => {
// user authenticated
if (authResult && authResult.accessToken && authResult.idToken) {
// setting authenticated to true
this.isAuthenticated = true;
// get expirity date
this.expirityTimestamp = jwt.decode(authResult.accessToken).expires
}
});
}
get authenticated(){
if(this.isAuthenticated && Date.now() < this.expirityTimestamp)
return true;
else
// here I should refresh the token then.
return false
}
As you mentioned the quickstart shows one possible way of accomplishing it. It’s not practical and likely not possible to try to cover all the possible requirements in a quickstart. For example, should a quickstart prioritise code performance over simplicity? Personally I would favour code simplicity and try to point to the important parts that need to be done and not overthink how exactly they should be done.
The important part is that you’ll most likely need to have the notion of authenticated vs non-authenticated, but the exact details will vary.
In relation to your proposed example I have just one note, access tokens are issued to client applications with the premise that they are opaque tokens that will then be sent to the corresponding resource server. The client application should not make any assumption on the format of the access token itself, so when you decode the access token as a JWT you’re assuming that the token will always be a JWT while in fact that format is agreed between the authorization server and resource server and technically the client application should not make any assumptions. An OAuth2 authorization response containing the access token will also most likely include a expires_in response parameter that states the lifetime of the access token so you may want to use that instead.