'How to get bearer token from auth0 Angular

How Should I get the Auth0 bearer token in Angular. I am currently using Auth0 SDK and AuthModule to set it up.

@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);
  }
}

and app.module.ts

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

I just want to get a way to get bearer token from auth0, I tried implementing getTokenSilently(), didn't work maybe I implemented wrong but I am not sure.

Thank you for the help.



Solution 1:[1]

You can refer this example and source code while dealing with Authorization headers and Tokens.

// src/app/auth/secure-interceptor.service.ts
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth.service';
import { Observable, throwError } from 'rxjs';
import { filter, mergeMap, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SecureInterceptor implements HttpInterceptor {

  constructor(private auth: AuthService) { }

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (req.url.indexOf('/secure/') > -1) {
      return this.auth.accessToken$.pipe(
        filter(token => typeof token === 'string'),
        mergeMap(token => {
          const tokenReq = req.clone({
            setHeaders: { Authorization: `Bearer ${token}` }
          });
          return next.handle(tokenReq);
        }),
        catchError(err => throwError(err))
      );
    }
    return next.handle(req);
  }
}

Source - https://kmaida.gitbooks.io/auth0-angular-workshop/content/token-interceptor-service.html

Solution 2:[2]

The best way to use auth0 in an angular application where you are calling api from a backend, I have tried my best to explain it.

This is a service I created to use http requests to the backend, service basically helps to make all the API call through 1 file.

Admin.service.ts

   @Injectable({ providedIn: 'root' })
    export class AdminService {
    
        equipment= []
    
        constructor(
            private http: HttpClient, 
        
            ) {
        }
    
        equipmentlist(){
            this.equipment.length = 0;
            this.http.get(`${environment.apiUrl}/admin/equipmentlist`).toPromise().then(data => {
            for(let key in data)
                    if(data.hasOwnProperty(key))
                        this.equipment.push(data[key]);
    
            });
    
            return this.equipment;
        }
}

and app.module.ts

enum CacheStorage {
  LocalStorage = "localStorage",
  SessionStorage = "sessionStorage"
}

      @NgModule({
      bootstrap: [AppComponent],
      imports: [
     AuthModule.forRoot({ 
    ...env.auth,
    cacheLocation: 'localstorage',
     // The AuthHttpInterceptor configuration
    ...env.authapi,
    }),
      ],
      providers: [
       AuthGuard,
       Validators,
       { provide: HTTP_INTERCEPTORS, useClass: AuthHttpInterceptor,  multi: true }
      ]
    })
    export class AppModule {}

Dont forget to configure your enviornment.ts file so the entire thing works compelete.

export const environment = {
  production: false,
  apiUrl: "https://localhost:7004",
    auth:{
      domain:  ,
      clientId: ,
      scope:,
      redirectUri: ,
      apiUrl:"https://localhost:7004/",
      audience: ,
      useRefreshTokens: true,
  },
  authapi:{
    httpInterceptor: {
      allowedList: [
        // YOUR backend API - specifically the protected ones 
        'https://localhost:7004/admin/*'
        ],
    }
  }, 

You can find more related article on Auth0's Docs I personally didn't find it very useful but they are extensive and gradually it does start making sense.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman
Solution 2 Nisarg Patel