使用Interceptor angular 6自动执行RefreshToken

时间:2018-12-12 04:41:06

标签: angular interceptor

当我使用拦截器自动刷新令牌时,出现以下错误:

  

您在期望流的位置提供了“未定义”。您可以提供   可观察,可承诺,可数组或可迭代。

这是我的代码:

import { Injectable, Injector } from '@angular/core';
import {
    HttpEvent, HttpInterceptor, HttpHandler, HttpRequest,
    HttpErrorResponse, HttpClient
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, mergeMap, map } from 'rxjs/operators';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { UserToken } from '../models/user-token.model';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    constructor(
        private injector: Injector,
        private route: Router,
        private authService: AuthService) {
    }
    private modifyRequest(req) {
        return req.clone({ setHeaders: { 'Content-Type': 'application/json', 'authorization': `bearer ${this.authService.getAccessToken()} ` } });
    }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if ((req.url.includes('login')) || (req.url.includes('token'))) {
            console.log("Authenticated");
        }
        else {
            if (localStorage.getItem('token')) {
                return next.handle(this.modifyRequest(req)).pipe(
                    catchError(error => {
                        if (error instanceof HttpErrorResponse) {
                            switch (error.status) {
                                case 401:
                                    this.authService.getTokenFromRefreshToken().subscribe((data: UserToken) => {
                                        if (data) {
                                            return next.handle(this.modifyRequest(req));
                                        }
                                        else {
                                            return this.authService.logOut();
                                        }
                                    })
                            }
                        } else {
                            return throwError(error);
                        }
                    })
                );
            } else {
                return next.handle(req);
            }
        }
    }
}

这是我的服务

import { Injectable } from '@angular/core';
import { Router } from "@angular/router";
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ResponseBody } from '../models/response-body.model';
import { map, share } from '../../../node_modules/rxjs/operators';
import { UserToken } from '../models/user-token.model';
import { UserInformation } from '../models/user-information.model';
const AUTH_API = '/api/auth';
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class AuthService {

  constructor(
    private httpClient: HttpClient,
    private router: Router) { }

  logOut() {
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
    this.router.navigate(['/login']);
  }
  refreshAccessToken(): any {
    localStorage.getItem("refreshToken");
  }
  getAccessToken(): string {
    return localStorage.getItem('token');
  }
  getRefreshToken(): string {
    return localStorage.getItem('refreshtoken');
  }
  setToken(token: string) {
    localStorage.setItem('token', token);
  }
  setRefreshToken(refreshToken: string) {
    localStorage.setItem('refreshToken', refreshToken);
  }
  getTokenFromRefreshToken() {
    let user = new UserToken();
    let refreshToken = this.getRefreshToken();
    user.refreshToken = refreshToken;
    let requestBody = user;
    return this.httpClient.post<ResponseBody>(`${AUTH_API}/refreshtoken`, requestBody, httpOptions)
      .pipe(
        share(),
        map(responseBody => {
          if (!responseBody.data || responseBody.data.length === 0) {
            return [];
          }
          let auth: UserToken = responseBody.data[0];
          this.setToken(auth.token)
          this.setRefreshToken(auth.refreshToken)
          return auth
        })
      )
  }
  getTokenFromApi(user: UserInformation) {
    let requestBody = user;
    return this.httpClient.post<ResponseBody>(`${AUTH_API}/login`, requestBody, httpOptions)
      .pipe(
        map(responseBody => {
          if (!responseBody.data || responseBody.data.length === 0) {
            return [];
          }
          let auth: UserToken = responseBody.data[0];
          this.setToken(auth.token)
          this.setRefreshToken(auth.refreshToken)
          return auth;
        })
      )
  }
}

0 个答案:

没有答案