Skip to main content
Version: 3.x

Checking Authentication Status

Auth Connect provides the isAuthenticated() convenience method for checking if there is a current session and refreshing that session if it is already expired.

However, there are cases where you may want to implement your own method for checking if the user is authenticated. An example of needing to do this would be to handle checking the authentication status when the device is offline.

The isAuthenticated() method relies on the application having a connection to the internet because if the access token is expired, it will automatically attempt to refresh that token with the authentication provider. If the device is not connected to the network during this check, the refresh attempt will fail and the method will report back that the user is not currently authenticated.

Auth Connect provides access to the various building blocks necessary to create your own method for checking authentication status. A simple example for gracefully handling offline might look like the following:

async function isUserAuthenticated(): Promise<boolean> {
if (!(await myAuth.isAccessTokenAvailable())) {
// No token available, not logged in
return false;
}
if (await myAuth.isAccessTokenExpired()) {
if (navigator.onLine) {
// Token is expired, but we have a connection so we will attempt to refresh the token
try {
await myAuth.refreshSession();
return true;
} catch (e) {
// Refresh failed, clear the storage
await myAuth.clearStorage();
return false;
}
} else {
// Token is expired, but no connection. We will check for the presence
// of a refresh token, and if it exists, we will assume the login is still valid
return !!(await myAuth.getRefreshToken());
}
} else {
// Access token is not expired, authentication is valid
return true;
}
}