如何使用Angular Http拦截器和RxJS刷新JWT令牌?

时间:2018-10-11 21:53:36

标签: javascript node.js angular express rxjs

我正在使用两个JWT令牌-Refresh Token(7天后过期)和Access Token(15分钟后过期)。它们存储在httpOnly cookies上,并且可以通过服务器进行访问。刷新方法对新令牌进行签名并将其存储在cookie中。我需要检查每个请求之后这些令牌是否已过期:

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private authService: AuthService, private cookieService: CookieService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            const expirationToken = this.cookieService.get('tokenexp'); // access token expiration
            const expirationTokenRefresh = this.cookieService.get('tokenrefexp'); // refresh expiration
            
            // Refresh Token needs to be checked first
            if (Number(expirationTokenRefresh) < Date.now()) {
                // new refresh token is stored on cookie
                this.authService.refreshTokenRefresh();
                // this.authService.refreshToken().subscribe(() => { ... });
            }
            // next we check Access Token
            if (Number(expirationToken) < Date.now()) {
              // new access token is stored on cookie
              this.authService.refreshToken();
         // this.authService.refreshTokenRefresh().subscribe(() => { ... });
            }
            return next.handle(req.clone({
                withCredentials: true
            }));
    }

}

// auth service
refreshToken() {
  return this.http.get(`${BACKEND_URL}/refreshtoken`);
}
refreshTokenRefresh() {
  return this.http.get(`${BACKEND_URL}/refreshtokenref`);
}

这是Express个后端方法:

//routes
const express = require('express');
const router = express.Router();
router.get('/refreshtoken', user.refreshToken);
router.get('/refreshtokenref', user.refreshTokenRefresh);

// refresh access token method
const jwt = require('jsonwebtoken');
const moment = require('moment');
const User = require('../models/user');
exports.refreshToken = wrap(async(req, res, next) => {
    const user = await User.findOne({ refresh_token: req.cookies['tokenref'] });
    if (user) {
        const newToken = await jwt.sign(
            { email: user.email, userId: user._id, role: user.role },
            process.env.JWT_Key,
            { expiresIn: '15m' });
        const expiresAt = moment().add(900, 'second');
        res.cookie('tokenexp', JSON.stringify(expiresAt.valueOf()), { maxAge: 3000000000, secure: true});
        res.cookie('token', newToken, { maxAge: 3000000000, secure: true, httpOnly: true });
        res.status(200).json({success: true});
    } else {
        res.status(401).json({success: false, message: 'Sessão expirou.'});
    }
});

如何使用RxJS Observables使它工作?我可能会发送一个请求以刷新令牌,然后发送另一个请求以刷新第二个令牌,最后发送具有更新cookie的原始请求。总而言之,我可能需要先发送请求,然后再发送原始请求。 还有一个问题:AuthInterceptor在请求一两个(令牌)后不应该被调用。

1 个答案:

答案 0 :(得分:1)

使用mergeMap顺序检查令牌的有效性。

return of(Number(expirationTokenRefresh) < Date.now()).pipe(
  mergeMap(expire => expire
    ? this.authService.refreshTokenRefresh()
    : of(Number(expirationToken) < Date.now())
  ),
  mergeMap(expire => expire
    ? this.authService.refreshToken()
    : of(true)
  ),
  mergeMap(ok => next.handle(req.clone({ withCredentials: true })))
)