Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Code Reviews

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

66%
+2 −0
Code Reviews Setting the authentication token in an Angular application for generated API clients

This is a post of mine from Code Review Stack Exchange which did not get an answer yet. I am developing an Angular application that consumes an external REST API. I am using OpenAPI generator (Typ...

1 answer  ·  posted 3y ago by Alexei‭  ·  last activity 2y ago by Alexei‭

#2: Post edited by user avatar Alexei‭ · 2020-11-08T08:10:22Z (over 3 years ago)
removed useless tag
#1: Initial revision by user avatar Alexei‭ · 2020-10-21T12:27:08Z (over 3 years ago)
Setting the authentication token in an Angular application for generated API clients
This is [a post of mine](https://codereview.stackexchange.com/questions/230159/setting-the-token-for-api-client-generated-instances-in-an-angular-application) from [Code Review Stack Exchange](https://codereview.stackexchange.com/) which did not get an answer yet.

I am developing an Angular application that consumes an external REST API. I am using [OpenAPI generator][1] (TypeScript template) to generate the API clients.

The happy flow is the following:

- call a method that requires a username + password and get a token
- set the token on a configuration object 
- update the generated instance API client with that configuration (which should also receive a base path)
- use the instance API client to call a method

**`DataLakeSecurityClientCustomizationService`** 

This takes care of initializing the API clients and setting the token when this is refreshed.

    @Injectable({providedIn: "root"})
    export class DataLakeSecurityClientCustomizationService {
    
        constructor(
            private readonly defaultService: DefaultService,
            private readonly securityTagsService: SecurityTagsService,
            /* other generated API client service instances will be here */) {
        }
    
        init() {
            this.defaultService.configuration.basePath = environment.dataLakeSecurityApiBasePath;
            this.securityTagsService.configuration.basePath = environment.dataLakeSecurityApiBasePath;
        }
    
        setToken(token: string) {
            this.securityTagsService.configuration.accessToken = token;
            // all other used services will get the token here
        }
    }

**app.component.ts**

      private initDataLakeExtAuth() {
        this.dataLakeCustService.init();
    
        // trying to get a token ASAP to use for subsequent calls
        this.store.dispatch(RequestNewTokenAction());
      }
    
      ngOnInit(): void {
        this.initDataLakeExtAuth();
      }

**Authentication effect**

This handles getting the token which is happening outside of reducer's pure functions. I am using ngrx/store framework (Angular 8 version).

    @Injectable()
    export class DataLakeExtAuthEffects {
    
        constructor(
            private readonly actions$: Actions,
            private readonly dataLakeExtAuthService: DataLakeExtAuthService,
            private readonly store: Store<AppState>,
            private readonly logger: LoggingService,
            private readonly dataLakeSecurityClientCustomizationService: DataLakeSecurityClientCustomizationService
        ) { }
    
        getNewToken$ = createEffect(() => this.actions$.pipe(
            ofType(RequestNewTokenAction),
            switchMap(_ => {
                this.store.dispatch(LoadingStartedAction({ message: "Performing security level authentication ..."}));
    
                return this.dataLakeExtAuthService.getLoginToken().pipe(
                    tap(() => this.store.dispatch(LoadingEndedAction())),
                    catchError(err => {
                        this.store.dispatch(LoadingEndedAction());
                        this.logger.logErrorMessage("Error getting a Data Lake Security View token: " + err);
    
                        this.store.dispatch(NewTokenLoadCancelledAction());
                        return of<string>();
                    }));
                }),
            map((token: string) => {
                this.dataLakeSecurityClientCustomizationService.setToken(token);
    
                return NewTokenLoadedAction({token});
            }))
        );
    }

### The authentication service for the external REST API ###

    @Injectable({providedIn: "root"})
    export class DataLakeExtAuthService {
    
        credentials = DataLakeCredentials;
    
        constructor(private readonly defaultService: DefaultService,
                    private readonly logger: LoggingService) {
        }
    
        getLoginToken(): Observable<string> {
            const token$ = this.defaultService.loginTokenPost(this.credentials.username, this.credentials.password)
                .pipe(
                    map((payload: { access_token: string }) => payload.access_token),
                    tap((token: string) => {
                        this.logger.logTrace("Received token: ", token);
                    })
                );
            return token$;
        }
    }

`DefaultService` is an automatically generated TypeScript class that actually performs the API call.

I am looking for improvement suggestions (code quality, performance is less relevant here). 

**Note:** I cannot control what code is generated through the OpenAPI generator.


  [1]: https://openapi-generator.tech/