1

I'm relatively new to Angular5/TypeScript, so I apologize for the (maybe) trivial question.

I'm trying to implement an authentication service which I intend to use in order to let my Angular5 frontend, consume some REST API exposed by a wordpress backend.

So far the service is implemented and working. What I'm missing, right now is a way to inject login data into REST requests.

To be more precise, I know how to do that but I don't now how to access the login information that I've previously stored in my shared service.

But let me be even more specific and let me share my code:

// auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

import { JwtHelperService } from '@auth0/angular-jwt';

interface IUser
{
    token: string,
    token_expires: number,
    user_display_name: string,
}

@Injectable()
export class AuthService
{
    private currentUser: IUser = null;
    private nonce: string = '';

    constructor(
        private http: HttpClient,
        private jwt: JwtHelperService,
    )
    {
        // set User Info if saved in local/session storage
        .
        .
        .
    }

    logIn(username: string, password: string, persist: boolean): Observable<boolean>
    {
        return this.http.post(
            API_BASE_DOMAIN + API_BASE_PATH + '/jwt-auth/v1/token',
            { username: username, password: password },
            {
                observe: 'response', // Full response instead of the body only
                withCredentials: true, // Send cookies
            }
        ).map(response  => {
            this.nonce = response.headers.get('X-WP-Nonce');
            const body: any = response.body

            // login successful if there's a jwt token in the response
            if (body.token)
            {
                // set current user data
                this.currentUser = <IUser>body;

                // store username and jwt token in local storage to keep user logged in between page refreshes
                let storage = (persist) ? localStorage : sessionStorage;
                storage.setItem('currentUser', JSON.stringify(this.currentUser));

                // return true to indicate successful login
                return true;
            }
            else
            {
                // return false to indicate failed login
                return false;
            }
        });
    }

    getNonce(): string
    {
        console.log((this.nonce) ? this.nonce : '');
        return (this.nonce) ? this.nonce : '';
    }

    getToken(): string
    {
        console.log((this.currentUser) ? this.currentUser.token : '');
        return (this.currentUser) ? this.currentUser.token : '';
    }
}



// app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { JwtModule } from '@auth0/angular-jwt';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';

import { AuthService } from './main/auth/services/auth.service';
import { AuthGuardService } from './main/auth/services/auth-guard.service';

import { API_BASE_DOMAIN } from './main/auth/services/auth.service';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { NonceHttpInterceptor } from './main/auth/auth.interceptor';

const appRoutes: Routes = [
   .
   .
   .
];


@NgModule({
    declarations: [
        AppComponent
    ],
    imports     : [
        BrowserModule,
        HttpClientModule,
        RouterModule.forRoot(appRoutes),

        // Jwt Token Injection
        JwtModule.forRoot({
            config: {
                tokenGetter: (***AuthService?????***).getToken,
                whitelistedDomains: [ API_BASE_DOMAIN ]
            }
        })
    ],
    providers   : [
        AuthService,
        AuthGuardService,
        {
          provide: HTTP_INTERCEPTORS,
          useClass: NonceHttpInterceptor,
          multi: true
        }
    ],
    bootstrap   : [
        AppComponent
    ]
})

export class AppModule
{
}

As you can see in my code at //JWT Token Injection, I need to specify a token getter which is implemented in my auth.service.

In a component file I can access its public methods by injecting the service as a parameter for the constructor, like this:

//login.component.ts
import { AuthService } from '../services/auth.service';

@Component({
      .
      .
      .
})

export class MyLoginComponent implements OnInit
{
    constructor(
        private authService: AuthService,
    )
    {
      .
      .
      .
    }

    onFormSubmit()
    {
        this.authService.logIn(uname, pwd, persist)
            .subscribe(
               .
               .
               .
            );
    }
}

But I don't seem to find a way to access a service method at module level!

I know, I could use static access for my tokenGetter and move everything at class level instead of instance level (like this: AuthService.getToken) but I think there is a better, more elegant way to access the getToken() method.

Thank you in advance for any hint/help.

  • I'm confused, why do you need to use your service in a module? – bugs Apr 13 '18 at 11:11
  • @bugs Actually it is not my choice. As you can see, I'm using a third party library for handling JWT authorization/authentication. This library declares *its* module (`forRoot()`) in order to implement authorizations headers injection. And its forRoot() initializer needs a function that provides the value for the authorization header to be injected. I know, they could have thought of some other way, but it's the way it is implemented and i cannot change it. –  Apr 13 '18 at 11:17
  • See here https://stackoverflow.com/questions/45405914/how-to-pass-dependencies-to-auth0-angular-jwt – David Apr 13 '18 at 11:31
  • @David. Really helpful David! Yes! It works! I've had minor problems with circular dependencies with JWT_OPTIONS but I managed to accomodate it. Thank you again. If you post your comment as answer, I'll mark it as the accepted one. –  Apr 14 '18 at 14:17

1 Answers1

2

Angular2-jwt supports using a custom options factory function, for specific cases like when

tokenGetter function relies on a service

Define the factory function like this

export function jwtOptionsFactory(authService: AuthService) {
  return {
    tokenGetter: () => {return authService.getToken();},
    whitelistedDomains: [ API_BASE_DOMAIN ]
  }
}

Then declare that function as a factory for the JWT_OPTIONS token

imports: [
JwtModule.forRoot({
  jwtOptionsProvider: {
    provide: JWT_OPTIONS,
    useFactory: jwtOptionsFactory,
    deps: [AuthService]
  }
})
],

NOTE: If a jwtOptionsFactory is defined, then config is ignored. Both configuration alternatives can't be defined at the same time.

David
  • 33,444
  • 11
  • 80
  • 118