Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve URL State When Logging in With angular-oauth2-oidc

Tags:

angular

We are using angular-oauth2-oidc to manage authentication in our Angular app. We're using the Code Flow with PKCE. We want the user to be automatically logged in when they visit the app, so our app is started like this:

this.oauthService.configure(authModuleObject);
this.oauthService.loadDiscoveryDocumentAndLogin();

We landed on this due to the documentation's recommendation. That works just fine. The issue is that if the user comes to the app on a child route (https://myapp.com/some/child/route), and are sent to log in, they come back to the home route again and there's no way to get to the originally requested page.

I've tried following the documentation here to get it working, but it doesn't seem to work with the loadDiscoveryDocumentAndLogin method.

I tried passing the state in to the method on an object:

this.oauthService.loadDiscoveryDocumentAndLogin({ state: 'xxx' })

But that doesn't do anything. I also added the onTokenReceived method on the options object like the documentation shows, but nothing seems to happen. I can't get access to the state, and it's not been preserved.

This would be a really convenient feature to implement for our users, so I'd like to get it working, but so far I can't get it there.

like image 705
pjlamb12 Avatar asked Sep 16 '25 13:09

pjlamb12


1 Answers

onTokenReceived was also not working for me, but I had luck with the then() function. In my example I put the url into the state, when I initiate the login. After the login, I read the url from the state and can redirect the user to the subpage.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  authenticationChecked = false;

  constructor(
    @Inject(PLATFORM_ID) private platformId,
    private oAuthService: OAuthService,
    private router: Router) {
  }

  ngOnInit(): void {
    if (isPlatformBrowser(this.platformId)) {
      this.oAuthService.configure(authCodeFlowConfig);
      this.oAuthService.setStorage(sessionStorage);

      this.oAuthService.loadDiscoveryDocumentAndTryLogin().then(() => {
        const url = this.oAuthService.state;

        if (!!url) {
          this.router.navigateByUrl(decodeURIComponent(url)).then()
        }

        this.authenticationChecked = true;
      });
    }
  }
}

init code

  initLogin() {
    if (isPlatformBrowser(this.platformId)) {
      if (this.isNotLoggedIn()) {
        this.oAuthService.initLoginFlow(this.router.url)
      }
    }
  }
like image 161
Marc Bellmann Avatar answered Sep 18 '25 10:09

Marc Bellmann