Okta-Auth-js with angular

Hi,
I am using angular 19 with okta-auth0js 7.8.1.In my app am seeing that after one hour of activity okta idtoken is expiring and okta-auth-js is reauthenticating with okta and automatically redirecting the user to home page.This flow is same as when the user first logs into the app.Now the issue is user is losing any unsaved data as the app is redirecting to home page.

Is there a way I could handle the okta call back and make the user to stay on the same page rather then being redirected.Any insights or git hub repo links or reference links is really appreciated.

Thanks

QQ, are you using okta-angular or are you using okta-auth-js directly?

Most likely autoRenew is enabled by default in your application and that is what is handling that re-authentication when the user’s first set of tokens expire. This autoRenew is done one of two ways:

  • if the user has an active refresh token in storage (returned when offline_access scope is requested)
  • if the user does NOT have a valid refresh token, the SDK will use an iframe to silently request tokens for a user, which will only work if the application is able to access the cookies set for the user on the Okta domain (aka, the application is either hosted on the same domain as the Okta tenant OR third-party cookies are disabled in the user’s browser)

I wouldn’t have expected the user to be redirected under either of those circumstances though, so you might be seeing this because the user lacks a valid refresh token AND the app cannot access an active Okta session (either because their Okta session expired or because it cannot reach the cookie set on the Okta domain).

You may want to move to passive autoRenew so that new tokens are only requested when they are needed, instead of when they expire, as described here: okta-auth-js/docs/autoRenew-notice.md at master · okta/okta-auth-js · GitHub and here GitHub - okta/okta-auth-js: The official js wrapper around Okta's auth API

Thanks for the response.I am using okta-auth-js directly in my SPA.Also I did try the configuration settings specified in okta-auth-js/docs/autoRenew-notice.md at master · okta/okta-auth-js · GitHub but this time its logging off the user from the app and asking the user to sign in again.I want the user to continue to remain logged in on the same page as he was..also i forgot to mention that even though id token had an expiry of 1 hour the access token was still active and has 24 hrs expiry.So I go back to my original question..can i handle this in the okta call back reauthentication to restore user session?Please suggest if anyone has faced similar issue and what was the workaround?Also wanted to mention that refresh_token is currently not enabled for this app.

@andrea any updates for me?

Is there a reason that you have chosen to not enable refresh tokens on the app?

Using refresh tokens to keep a users session active will be least disruptive to the end users and I would definitely recommend enabling it (on the app within Okta Admin Console AND by requesting the offline_access scope when configuring AuthJS) to see how it can help with this behavior.

Hi Andrea,
Currently there is no issue in token renewal.Tokens are getting renewed but the issue is with user getting redirected to home page after okta re-athentication rather than continue on the same page.Trying to trouble shoot the issue as to why user is getting redirected to home page..so far I tried removing RoleGuard and AuthGuard assming they were the issue but that is not the case.Even set the originalUri attribute in aktaAuth before token expiry. In my custom callback component I printed the originalUri and it looks good but user still gets redirected to /home route.The route URL also looks good..But unabel to figure out why user is being redirected to home page.One thing I noticed was when trying to parse the tokens from URL am getting an error saying “Unable to parse a token from the URL”.The code am using is await this.oktaAuth.token.parseFromUrl(); which is causing the error..Do you think that is the reason for user being redirected to home page?am I calling redirect too soon even before the token manager has the tokens?If yes how to address this?

This behavior implies to me that your application is kicking off a full authorization flow to get new tokens for the user, which would involve the user routing through your callback route and being redirected wherever your callback route says to redirect them (which as you mention, should be the originalUri). I do not recognise the behavior you are seeing and I’ve not seen it occur with the okta-angular SDK’s sample application, so I can’t say I know what would cause this.

Using a refresh token should not result in such a redirect, as a request to /authorize does not occur and the app would instead make a POST request to get new tokens. Unless your application is designed to redirect, I couldn’t imagine it would do the same thing using refresh tokens

One thing I noticed was when trying to parse the tokens from URL am getting an error saying “Unable to parse a token from the URL”.The code am using is await this.oktaAuth.token.parseFromUrl();

What is causing the user to get redirect back to the callback route? If you inspect the network traffic, do you see a “code=xxxx” parameter being sent to your callback route (indicating that an /authorize call caused the redirect)?

Maybe I should also ask this, but are you using Authorization Code Flow with PKCE or are you using Implicit flow? We would definitely recommend using Auth Code Flow, and that flow will allow the application to request and receive Refresh Tokens.

Hi Andrea,
The flow am seeing for the token expiry and okta reauthentication is same as the login flow..I do see a call /authorize and /token and on /login/callback i do see the code parameter…I am using Authorization code flow with PKCE.And for the refresh tokens we are told it wont be enabled as this is an in house app.Is there a way this can be addressed without the refresh token?Also if its full authorization code flow will it always redirect to /home route?We cannot override that by setting originalUrl attribute to redirect user to the same page he was before token expiry?

Hi Andrea,
just wanted a confirmation so that I could update in my org that we need to the refresh token enabled for this to work.Please let me know

You might want to look into what your callback route is doing when handling the redirect. Does it look anything like we recommend in the AuthJS readme?

  // Handle callback
  if (authClient.token.isLoginRedirect()) {
    const { tokens } = await authClient.token.parseFromUrl(); // remember to "await" this async call
    authClient.tokenManager.setTokens(tokens);
  }

AuthJS shouldn’t be redirecting to the originalUrI unless you’ve told it to do so, such as by using the handleLoginRedirect/handleRedirect method instead of parseFromUrL.

Can you share your code for your callback component?

callback component

async ngOnInit() {
try {

  const result = await this.oktaService.handleCallback();
  await this._oktaAuth.handleRedirect();
}catch(err) {
  console.error('Error hadnling redirect: ', err);
}

}

okta service
async handleCallback() {
try {
console.log(‘inside handlecallback’);
const response = await this.oktaAuth.token.parseFromUrl();
console.log(response);
if (response.tokens) {
if (response.tokens.idToken) {
await this.oktaAuth.tokenManager.add(‘idToken’, response.tokens.idToken);
}
if (response.tokens.accessToken) {
await this.oktaAuth.tokenManager.add(‘accessToken’, response.tokens.accessToken);
}
}
return “successful”;
} catch (error: any) {
return error;
}
}

Hi Andrea,
Any update for me plz?

@andrea Did you get a chance to check the code i shared?

@andrea Please suggest

Wait, so you are using handleRedirect? Because that method absolutely will redirect the user away from the page they are currently on:


By default it calls window.location.replace for the redirection. The default behavior can be overrided by providing options.restoreOriginalUri. By default, originalUri will be retrieved from storage, but this can be overridden by specifying originalUri in the first parameter to this function.

Is there a reason you are not using our Angular SDK and are using AuthJS directly? I wonder if it might make some things simpler for you

Hi Andrea,
Thank you for the response. I tried even overriding the originalUri on token expiry but even that is not working.I added event listener for token expiry and setting the originalUri.

constructor(private router: Router, private dialog: MatDialog, private cookie: CookieService,
private dataSharingService: DataSharingService, private _oktaStateService: OktaAuthStateService,
@Inject(OKTA_AUTH) private _oktaAuth: OktaAuth, private oktaService: OktaService, private httpClientService: HttpClientService) {

  _oktaAuth.tokenManager.on('expired', async(key) => {
    console.log(`Token with key ${key} has expired`);
    try {
      console.log('inside try');
      _oktaAuth.setOriginalUri(encodeURI(window.location.href));
     // await this._oktaAuth.signInWithRedirect();
      
    }catch(err){
      console.log('inside error');
      console.error(`Tokenmanager error`,err);
      
      _oktaAuth.token.getWithRedirect();
    }
  });



  // _oktaAuth.start();

}

in my custom callback component

async ngOnInit() {
try {

  const result = await this.oktaService.handleCallback();

  await this._oktaAuth.handleRedirect();
}catch(err) {
  console.error('Error hadnling redirect: ', err);
}

}

Please let me know where am going wrong..and yes currently we are using okta auth js..please share the reference link for okta angular if it can fix this issue then I can definitely leverage that

What about switching to using parseFromUrl and setTokens? That only does parts of what handleRedirect does and then your callback component can decide where to redirect the user

You can find information about our Angular SDK in its readme here: GitHub - okta/okta-angular: Angular SDK for Okta's OIDC flow

@andrea so we cant fix this with okta-auth-js?

the code I shared earlier is for AuthJS, it came from the readme here: GitHub - okta/okta-auth-js: The official js wrapper around Okta's auth API