0

I have the following requirement that I find challenging to implement in Angular. After the user authenticates using and Auth Provider, I need to load his/her roles from backend. Base on roles I need to show certain pages. I want to accomplish this with and APP_INITIALIZER. It looks like this:

export function initRolesFactory(bootstrapService: BootstrapService): Function {
  return () => bootstrapService.loadUserRoles();
}
...
 { provide: APP_INITIALIZER, useFactory: initRolesFactory, deps: [BootstrapService], multi: true }

...
@Injectable()
export class BootstrapService {

roles: string;

constructor(private http: HttpClient) {}

loadUserRoles() {
        this.http.get<string>('http://localhost:8080/api/roles').subscribe({
        next: data =>{ 
            this.roles = data;
            console.log('Roles', this.roles);
        },
        error: err => console.log(err)
    })  
}

With this code I get Circular dependency in DI detected for OidcSecurityService. I suppose that an HttpInterceptor that is responsible for injecting token into request is "guilty."

HttpInterceptor:

 @Injectable()
 export class TokenInterceptor implements HttpInterceptor {

constructor(private authService: OidcSecurityService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.authService.getAccessToken().pipe(
        switchMap(token => {
        if (token) {
            request = request.clone({
                setHeaders: { Authorization: `Bearer ${token}` }
            });
        }
        return next.handle(request);
        })
    );
}

}

I have also tried this solution:

 @Injectable()
 export class BootstrapService {

roles: string;

constructor(private httpBackend: HttpBackend, private injector: Injector) {}

loadUserRoles() {
    let oidcService: OidcSecurityService = this.injector.get(OidcSecurityService);
    let token = oidcService.getAccessToken().subscribe(token => {
        //Call backend with access token.
    });

}

}

This time I get an error because AuthConfigService (a service that I use to configure StsConfigStaticLoader) is not loaded.

Long story short, how can I initiate a call to fetch roles after authentication, and before components are loaded?

Cosmin D
  • 639
  • 1
  • 11
  • 24

0 Answers0