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:
_26async function isUserAuthenticated(): Promise<boolean> {_26 if (!(await myAuth.isAccessTokenAvailable())) {_26 // No token available, not logged in_26 return false;_26 }_26 if (await myAuth.isAccessTokenExpired()) {_26 if (navigator.onLine) {_26 // Token is expired, but we have a connection so we will attempt to refresh the token_26 try {_26 await myAuth.refreshSession();_26 return true;_26 } catch (e) {_26 // Refresh failed, clear the storage_26 await myAuth.clearStorage();_26 return false;_26 }_26 } else {_26 // Token is expired, but no connection. We will check for the presence_26 // of a refresh token, and if it exists, we will assume the login is still valid_26 return !!(await myAuth.getRefreshToken());_26 }_26 } else {_26 // Access token is not expired, authentication is valid_26 return true;_26 }_26}