2

I need to configure dynamic URLs for the OAuthModule to send the access token at each request. The solution that I'm using (hint), providing an OAuthModuleConfig via a factory method, doesn't seem to work.

This is my AppModule where I configure everything:

import {BrowserModule} from '@angular/platform-browser';
import {APP_INITIALIZER, NgModule} from '@angular/core';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {OAuthModule, OAuthModuleConfig} from 'angular-oauth2-oidc';
import {HttpClientModule} from '@angular/common/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MaterialModule} from './material/material.module';
import {DataSharingService} from './data-sharing/data-sharing.service';
import {EnvironmentService} from './environment/environment.service';
import {environment} from '../environments/environment';
import {ApiModule, BASE_PATH} from '@api/api-client';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    APIModule,
    HttpClientModule,
    OAuthModule.forRoot(),
    BrowserAnimationsModule,
    MaterialModule
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: appInitializerFactory,
      deps: [EnvironmentService, DataSharingService],
      multi: true
    },
    {
      provide: OAuthModuleConfig,
      useFactory: oAuthModuleConfigFactory,
      deps: [DataSharingService]
    },
    {
      provide: BASE_PATH,
      useFactory: basePathFactory,
      deps: [DataSharingService]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

function appInitializerFactory(environmentService: EnvironmentService, dataSharingService: DataSharingService): () => Promise<void> {
  return () => environmentService.getEnvironment(environment.production)
    .toPromise()
    .then(value => {
      dataSharingService.apiBasePath.next(value.API_BASE_PATH);
    });
}

function oAuthModuleConfigFactory(dataSharingService: DataSharingService): OAuthModuleConfig {
  return {
    resourceServer: {
      allowedUrls: [dataSharingService.apiBasePath.value],
      sendAccessToken: true
    }
  };
}

function basePathFactory(dataSharingService: DataSharingService): string {
  return dataSharingService.apiBasePath.value;
}

I think I should pass this configuration to the OAuthModule.forRoot() method in imports, but I don't know how.

How do I pass the provided OAuthModuleConfig to the OAuthModule.forRoot()?

Srijon Chakraborty
  • 2,007
  • 2
  • 7
  • 20
1Z10
  • 2,801
  • 7
  • 33
  • 82

0 Answers0