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 { }