我如何在 Angular 8 的 AuthInterceptor 类中获取/使用 accessToken [英] How can i get/use accessToken in AuthInterceptor class in Angular 8

查看:36
本文介绍了我如何在 Angular 8 的 AuthInterceptor 类中获取/使用 accessToken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在 AuthInterceptor 类中获取/使用 accessToken &将其添加到每个 API (.NetCore) 调用中.我已经实施了

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

在 authService 中,但我似乎无法在intercept(req: HttpRequest, next: HttpHandler){} 方法中使用它.我可以实施的任何方式或流程更改.

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.

推荐答案

首先,将你对 Observable 的承诺转换成你的 AuthService.ts :

First, convert your promise to an Observable into your 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())
  )
};

然后你可以很容易地在你的AuthHttpInterceptor中使用它:

Then you can use it easily into your 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);
      })
    );
  }
}

这篇关于我如何在 Angular 8 的 AuthInterceptor 类中获取/使用 accessToken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆