How can i get/use accessToken in AuthInterceptor class in Angular 8

Ber*_*ard 3 amazon-cognito angular aws-amplify

How can i get/use accessToken in AuthInterceptor class & adding it to every API (.NetCore) call. I've already implemented

 getAccessToken() {
    return Auth.currentSession().then(res => {
      return res.getAccessToken().getJwtToken();
    });
  }
Run Code Online (Sandbox Code Playgroud)

in authService, But i can't seem to use this in intercept(req: HttpRequest, next: HttpHandler){} method. Any way around or flow changes i can implement.

Thi*_*lvo 6

首先,将您的承诺转换Observable为您的AuthService.ts

import { from } from 'rxjs';
import { switchMap } from 'rxjs/operators';

...

getAccessToken(): Observable<string> {
  return from(Auth.currentSession()).pipe(
    switchMap(session => from(session.getAccessToken().getJwtToken())
  )
};

Run Code Online (Sandbox Code Playgroud)

然后您可以轻松地将它用于您的AuthHttpInterceptor

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
  constructor(
    private authService: AuthService
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.authService.getAccessToken().pipe(
      switchMap(jwtToken => {
        // clone the request to add the new header.
        const authReq = req.clone({ 
          headers: req.headers.set('Authorization', `Bearer ${jwtToken}`) 
        });
        return next.handle(authReq);
      })
    );
  }
}

Run Code Online (Sandbox Code Playgroud)

  • 它应该是 `of(session.getAccessToken().getJwtToken()); ` 在服务文件中,否则它将返回字符数组而不是整个字符串作为标记。 (4认同)