Malte
Malte

Reputation: 351

Auth0 bearer token in angular service

I have an angular service that triggers different rest request to a backend system. I want to add an authentication based on auth0 to the http header which is defined the constant before the class is defined.

SERVICE

const ZUORA_URL = 'https://jangoepelapitest.azure-api.net/gocsso';
const headers = new HttpHeaders({
  'Access-Control-Allow-Origin': '*',
  'Authorization': 'Bearer ***TOKEN***',
  'Content-Type': 'application/json'
});

@Injectable({
  providedIn: 'root'
})
export class ZuoraService {
  constructor(private http: HttpClient) {}

  // INVOICES
  getInvoice(id: String): Observable<any> {
    return this.http.get(ZUORA_URL + '/v1/invoices/' + id + '/files', {
      headers
    });
  }

  reverseInvoice(id: String): Observable<any> {
    console.log('Invoice reversed');
    return this.http.put(ZUORA_URL + '/v1/invoices/' + id + '/reverse', {
      'applyEffectiveDate': '2017-02-20',
      'memoDate': '2017-02-20'
    }, {
      headers
    });
  }
...
}

The auth0 token generation works fine for testing I added the following code to the central app component:

APP COMPONENT

  constructor(public auth: AuthService) {
    auth.handleAuthentication();
  }
  ngOnInit() {
    console.log('AppComponent: OnInit()');
    if (localStorage.getItem('isLoggedIn') === 'true') {
      this.auth.renewTokens();
    }
  }

When I added the generated token into the header (copy/paste) the authorization works fine. How can add the generated token to header structure in the service?

cheers Malte

Upvotes: 0

Views: 178

Answers (2)

Maihan Nijat
Maihan Nijat

Reputation: 9355

Create a service for HTTP Interceptor:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(public auth: AuthService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const headers = new HttpHeaders({
    'Access-Control-Allow-Origin': '*',
    'Authorization': 'Bearer ***TOKEN***',
    'Content-Type': 'application/json'
    });

    request = request.clone({
      setHeaders: {
        headers
      }
    });

    return next.handle(request);
  }
}

Get the token from your OAuth Service and set it in the above class, headers authorization.

And add interceptor to your provider in the app.module.ts:

@NgModule({
  bootstrap: [AppComponent],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
  ]
})
export class AppModule {}

This sends token with each HTTP request.

Upvotes: 2

Martin Paucot
Martin Paucot

Reputation: 1251

You could use an HttpInterceptor, it will intercept the request before sending it and you can set an Header for your Bearer Token : https://angular.io/api/common/http/HttpInterceptor

And you can get your Token from a Service or directly from cookies or local storage.

Upvotes: 0

Related Questions