Angular 9/OAuth2/OIDC and Routing Issue

2.4k Views Asked by At

I have implemented a basic Oauth2/OIDC silent-refresh with the angular-oauth2-oidc API and am having some issues getting links to specific areas inside my application to work.

For instance, the application generates emails for users to reach a certain page. When that link is clicked, the page is rendered for a moment, then there is a reload which appears to come from the OAuth request, and the application returns to the initial page.

    export class AppComponent implements OnInit {
      private authConfig: AuthConfig;
      constructor(
        private oauthService: OAuthService,
        private location: Location,
      ) {
        console.log("AppComponent:constructor");
        this.configureOAuth();
      }
    
      ngOnInit() {
      }
    
      private configureOAuth() {
        this.authConfig = {
          issuer: this.getIssuer(),
          clientId: environment.clientId,
          scope: 'openid profile email preferred_username',
          responseType: 'code',
          redirectUri: `${window.location.origin}/`,
          silentRefreshRedirectUri: `${window.location.origin}/silent-renew.html`,
          useSilentRefresh: true,
          showDebugInformation: true,
        };
    
        this.oauthService.configure(this.authConfig);
        this.oauthService.setStorage(sessionStorage);
        this.oauthService.setupAutomaticSilentRefresh();
    
        this.oauthService.loadDiscoveryDocumentAndLogin();
     }

My AppComponent appears to be getting loaded twice in the console log:

Navigated to: https://localhost:44306/action/1234
AppComponent:constructor
HttpRequestInterceptor: hasValidAccessToken:  https://auth.myhost.com/.well-known/openid-configuration
HttpRequestInterceptor: hasValidAccessToken:  https://auth.myhost.com/pf/JWKS
oauth/oidc event discovery_document_loaded
oauth/oidc event discovery_document_loaded

Navigated to https://localhost:44306/?code=b5dcWoxpFnc2Z9lfaCJaVWoj-l0oEpo1AG8AAAAG&state=VGplenktRWZ3N21aNDh5UHdlSVMyMGJOVEJheDBMa0lTeU1kaGR1OTRoSy5Y

AppComponent:constructor
oauth/oidc event discovery_document_loaded
oauth/oidc event discovery_document_loaded
http-request-interceptor.service.ts:25 HttpRequestInterceptor: hasValidAccessToken:  https://auth.myhost.com/as/token.oauth2
refresh tokenResponse {access_token: "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx4cmdXck1EVV9nN3ROSV…Hq720zdSrR4UkPwBRTmfZIE0ZbLNHYl0v-DhNHChEBrSE0-OA", id_token: "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx4cmdXck1EVV9nN3ROSV…hynONaOjaeBKv63jKRm-m4VPC3JRysIRj0-zK4Y0C7VGdnjUA", token_type: "Bearer", expires_in: 7199}
oauth/oidc event token_received
oauth/oidc event token_refreshed

I assume I am missing something very simple here, but after spending the past 8 hours reading through the angular-oauth2-oidc docs,samples and googling for ideas, i'm coming up empty.

Thanks

1

There are 1 best solutions below

0
On

After a night's sleep and re-reading a few postings, I found the correct combination to get things working.

First off, in my RouterModule, I reconfigured to stop the initial navigation:

@NgModule({
  imports: [RouterModule.forRoot(routes, { initialNavigation: false })],

In my RouteGuard, I activate only once the token is retrieved:

  canActivate(
    route: ActivatedRouteSnapshot, state: RouterStateSnapshot
  ) {
    let hasIdToken = this.oauthService.hasValidIdToken();
    let hasAccessToken = this.oauthService.hasValidAccessToken();
    return (hasIdToken && hasAccessToken);
  }

And most importantly, in my AppComponent, I pass in the initial URL to initCodeFlow and use it upon return:

  constructor(
    private oauthService: OAuthService,
    private router: Router,
    private location: Location,
  ) {
    this.url = this.location.path(true);
    this.configureOAuth();
  }

  private configureOAuth() {
    this.authConfig = {
      issuer: this.getIssuer(),
      clientId: environment.clientId,
      scope: 'openid profile email preferred_username',
      responseType: 'code',
      redirectUri: `${window.location.origin}/`,
      silentRefreshRedirectUri: `${window.location.origin}/silent-renew.html`,
      useSilentRefresh: true,
    };
       
    this.oauthService.configure(this.authConfig);
    this.oauthService.setupAutomaticSilentRefresh();

    return this.oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
      if (this.oauthService.hasValidIdToken()) {
        if (this.oauthService.state) {
          this.router.navigateByUrl(decodeURIComponent(this.oauthService.state));
        }
        else {
          this.router.navigateByUrl('/');
        }
        this.isLoaded = true;
      } else {
        // init with requested URL so it can be retrieved on response from state
        this.oauthService.initCodeFlow(this.url);
      }
    });
  }