okta / okta-vue

OIDC SDK for Vue
https://github.com/okta/okta-vue
Other
46 stars 25 forks source link

$auth.IsAuthenticated() is returning false on a initial load. #140

Closed PavankalyanPayyavula closed 7 months ago

PavankalyanPayyavula commented 9 months ago

Describe the bug

When we login into app for the first time $auth.IsAuthenticated() is returning false on initial load. When we refresh the application then $auth.IsAuthenticated() is returning true.

Using Vue3, Composition API.

In main.js -->

import CONFIG from "./config";
export const oktaAuth = new OktaAuth({
  clientId: CONFIG.OKTA.CLIENT_ID,
  issuer: CONFIG.OKTA.ISSUER,
  redirectUri: CONFIG.OKTA.REDIRECT_URI,
  postLogoutRedirectUri: CONFIG.OKTA.POST_LOGOUT_REDIRECT_URI,
  scopes: ['openid', 'profile', 'email'],
  pkce: true
});
app.use(OktaVue, { oktaAuth });

In App.vue -->

<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script setup>
import axios from 'axios';
import { onMounted } from 'vue';
import { useAuth } from '@okta/okta-vue';
import { useLoggedInUserStore } from './stores/loggedInUser';
const $auth = useAuth();
const loggedInUser = useLoggedInUserStore();
onMounted(async () => {
  const isAuthenticated = await $auth.isAuthenticated();
  if (isAuthenticated) {
    const accessToken = $auth.getAccessToken();
    axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
    loggedInUser.getLoggedinUserFromAPI();
  }
});
</script>

Reproduction Steps?

By the configuration mentioned above, on the initial load await $auth.isAuthenticated() is failing to send the true.

SDK Versions

package.json

"@okta/okta-auth-js": "7.4.3",
"@okta/okta-vue": "5.7.0",

Additional Information

No response

PavankalyanPayyavula commented 8 months ago

Any update?

denysoblohin-okta commented 8 months ago

When you're being redirected to login callback page, it takes some time to obtain tokens and update auth state. So I recommend you to use $auth.authStateManager

    onMounted(() => {
      $auth.authStateManager.subscribe((authState) => {
        if (authState.isAuthenticated) {
          const accessToken = $auth.getAccessToken();
          axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
          loggedInUser.getLoggedinUserFromAPI();
        }
      });
    });