Logout user automatically if token renew wasn't renewed

I would like to know how to logout the user , if token expires. (can be when user tries to navigate)
i followed this GitHub - okta/samples-js-vue: samples-js-vue and am using okta-auth-js@7.4 and okta-vue@5.6

For adding custom behavior during token renewal, you could disable the default autoRenew feature and add your custom handler to token expired event. For example

const oktaAuthInstance = this.$auth;
    this.$auth.tokenManager.on('expired', function(key, expiredToken) {
      oktaAuthInstance.tokenManager.renew('accessToken')
        .then(function(freshToken) {
          // manage freshToken
        })
        .catch(function(err) {
          console.log(err);
          oktaAuthInstance.signOut();
        });
    })

Thank you for this code snippet. I was looking to something like this, but this seems to sign me back automatically once the token is expired

router.beforeEach(async(to) => {
const isAuthenticated = await oktaAuth.isAuthenticated();
if (to.meta.requiresAuth && !isAuthenticated) {
    await  oktaAuth.signInWithRedirect();
  } 
})

Hi, I’ve added a check to see if the user is authenticated and whether the token has expired. If the token is expired, the user will be logged out using oktaAuth.signOut() and redirected to the login page. Otherwise, the navigation will continue as usual. I took help from some experts and that turned out to be very beneficial for me.

Make sure to replace ‘/login’ with the actual path to your login route. Please edit accordingly…

import { oktaAuth } from '@okta/okta-auth-js';

router.beforeEach(async (to, from, next) => {
  const isAuthenticated = await oktaAuth.isAuthenticated();
  
  if (to.meta.requiresAuth && !isAuthenticated) {
    // User is not authenticated and the route requires authentication.
    // Redirect to Okta sign-in.
    await oktaAuth.signInWithRedirect();
  } else if (isAuthenticated) {
    // User is authenticated. Check if the token is expired.
    const tokenInfo = await oktaAuth.tokenManager.get('accessToken');
    
    if (tokenInfo && tokenInfo.expiresAt) {
      const currentTime = Math.floor(Date.now() / 1000);
      if (tokenInfo.expiresAt < currentTime) {
        // Token is expired. Perform logout and redirect to login page.
        await oktaAuth.signOut();
        next({ path: '/login' }); // Redirect to your login route.
        return;
      }
    }
  }
  
  // Continue with the navigation.
  next();
});

Thanks!

Thanks, but not working for me. It still signs me back in instead of logging out and taking user to okta login page. And jyfi am using vue3 and router 4+

Hi nyfer,

I understand that you’re having trouble logging out the user when the token expires. I’ve checked the code that I provided, and it should work in Vue 3 and Router 4+. Please make sure that:

You’re using the correct version of the Okta Auth JS library. The code that I provided is for version 7.4, so if you’re using a different version, you’ll need to update the code accordingly.
Make sure that you’re setting the meta.requiresAuth property on the routes that require authentication. This property tells the router to check if the user is authenticated before allowing them to navigate to the route.
Make sure that you’re calling the oktaAuth.signOut() method correctly. This method takes an optional callback function as an argument. If you don’t provide a callback function, the Okta Auth library will automatically redirect the user to the login page.

If you’ve checked all of these things and you’re still having trouble, please provide more details about your setup so that I can help you troubleshoot the issue, Or I can get help for you. In the meantime, try disabling your ad blocker. Ad blockers can sometimes block the Okta Auth library from working properly.