How do Autentification connection and manage session with “angular-oauth2-oidc”?

Issue

This Content is from Stack Overflow. Question asked by Jack Boch

I have client application Agular13 and Open id connect authentication server, in implicit flow mode.

So I used the “angular-oauth2-oidc” and “angular-oauth2-oidc-jwks” library to do this.

Actually I manage to connect and redirect to my home page,
But I can’t get the session information which is currently in the local storage, and I would also like to secure the pages by authentication and by role.

But the first time I only have the user information then I can’t access it, I get an empty object while I still have a token in the local starage.

import { Injectable } from "@angular/core";
import { AuthConfig, OAuthService, NullValidationHandler,  } from "angular-oauth2-oidc";
import { JwtHelperService } from "@auth0/angular-jwt";
import { filter } from "rxjs/operators";
import { Router } from "@angular/router";
import { JwksValidationHandler } from "angular-oauth2-oidc-jwks";

@Injectable({
  providedIn: "root",
})
export class InitialAuthService {
  private jwtHelper: JwtHelperService = new JwtHelperService();

  private _decodedAccessToken: any;
  private _decodedIDToken: any;
  get decodedAccessToken() {
    return this._decodedAccessToken;
  }
  get decodedIDToken() {
    return this._decodedIDToken;
  }

  constructor(
    private oauthService: OAuthService,
    private authConfig: AuthConfig,
    public router: Router,
  ) { }

  async initAuth(): Promise<any> {
    return new Promise<void>((resolveFn, rejectFn) => {

      this.oauthService.configure(this.authConfig);
      this.oauthService.setStorage(localStorage);
      this.oauthService.tokenValidationHandler = new JwksValidationHandler();

      this.oauthService.events
        .pipe(filter((e: any) => e.type === "token_received"))
        .subscribe(({ type }) => {
          this.handleNewToken();
        });

      this.oauthService.loadDiscoveryDocumentAndLogin().then(
        (isLoggedIn) => {
          if (isLoggedIn) {            
            this.oauthService.setupAutomaticSilentRefresh();
            resolveFn();
          } else {
            this.oauthService.initImplicitFlow();
            rejectFn();
          }
        },
        (error: { status: number; }) => {
          console.log({ error });
          if (error.status === 400) {
            location.reload();
          }
        }
      );
    });
  }

  private handleNewToken() {
    this._decodedAccessToken = this.jwtHelper.decodeToken(
      this.oauthService.getAccessToken()
    );
    this._decodedIDToken = this.jwtHelper.decodeToken(
      this.oauthService.getIdToken()
    );
  }

  logoutSession() {
    console.debug("logout");
    this.oauthService.logOut();
  }
}
import { TestBed } from '@angular/core/testing';
import { InitialAuthService } from './initial-auth.service';

describe('InitialAuthService', () => {
  let service: InitialAuthService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(InitialAuthService);
  });
  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});
import { APP_INITIALIZER, NgModule } from "@angular/core";
import { AuthConfig, OAuthModule, OAuthStorage } from "angular-oauth2-oidc"
import { InitialAuthService } from "./initial-auth.service";
import { environment } from "../../environments/environment";

const configAuthZero: AuthConfig = environment.idp;

export function storageFactory(): OAuthStorage {
  return localStorage
}

@NgModule({
  imports: [OAuthModule.forRoot()],
  providers: [
    InitialAuthService,
    { provide: AuthConfig, useValue: configAuthZero },
    { provide: OAuthStorage, useFactory: storageFactory },
    {
      provide: APP_INITIALIZER,
      useFactory: (initialAuthService: InitialAuthService) => () =>
        initialAuthService.initAuth(),
      deps: [InitialAuthService],
      multi: true,
    },
  ],
})
export class AuthModule { }
 issuer: issuer,
    redirectUri: redirectURL,
    clientId: 'implicit',
    scope: "openid",
    showDebugInformation: true,
    dummyClientSecret: secret,
    logoutUrl: logoutUrl+clientid,
    skipIssuerCheck:true,



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?