-1

Can someone check my code? The token is not making it to local storage and also not being attached with the token interceptor. When I check the network tab, it does not it the token endpoint. I know local storage is not the best but this app will be used within a private network. Imports were removed to save space.

TokenService to get the token:

@Injectable({
  providedIn: 'root'
})

export class TokenService {
  constructor(private http: HttpClient,) { }

  public getToken(): Observable<any> {

    const headers = new HttpHeaders({
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/x-www-form-urlencoded',
    })

    let body = new URLSearchParams()
    body.set('username', 'alison')
    body.set('grant_type', 'password')
    body.set('password', 'password')
    body.set('scope', 'Marketplace')
    body.set('client_id', 'Api')
    body.set('client_secret', 'Secret')

    return this.http.post<{ access_token: string }>(`${tokenURl}/connect/token`, body, { headers: headers })
      .pipe(
        tap(res => {
          localStorage.setItem('access_token', res.access_token);
          console.log('access_token:' + JSON.stringify(res.access_token));
        }));
  }

}

Token Interceptor code:


@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const isApiUrl = req.url.startsWith(Constants.apiRoot);
    const bearerToken = localStorage.getItem('access_token');
    if (isApiUrl) {
      req = req.clone({
        setHeaders: {
          'Content-Type': 'application/json;',
          'Accept': 'application/json',
          'Authorization': `Bearer ${bearerToken}`,
        },
      });
    }
    return next.handle(req);
  }
}

app.component.ts:

export class AppComponent {

  constructor(private tokenService: TokenService,) { }

  ngOnInit(): void {
    this.tokenService.getToken().subscribe(
      data => localStorage.setItem('access_token', data.access_token),
      err => console.log(err),
    );
  }
}

app.module.ts

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule,
    SharedModule,
    WorksheetModule,
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true
  }],
  bootstrap: [AppComponent],
})
export class AppModule { }

AlisonDev
  • 1
  • 4

1 Answers1

0

You did not subscribe to your this.tokenService.getToken() your service is returning back as an observable.

Change your onInit():

ngOnInit(): void {
   this.tokenService.getToken().subscribe();
}
penleychan
  • 5,370
  • 1
  • 17
  • 28
  • I have added your suggestion, good catch. Although when i check the network tab it doesnt even hit the token endpoint. – AlisonDev Mar 11 '21 at 20:02
  • @AlisonDev I don't see anything else that's out of place. Perhaps maybe comment out the providers for http interceptor to debug and possibly re serve your angular app. – penleychan Mar 11 '21 at 20:11