拦截器未设置授权令牌

时间:2018-07-18 08:18:09

标签: token httpclient interceptor angular6

嗨,我正在尝试编写一个简单的Angular 6拦截器,该拦截器在发送请求时将jwt令牌添加到标头中。

问题是请求中的标头在后端到达NULL,所以我当然无法获得授权令牌,而且我很难弄清原因。

我非常确定问题出在我的js代码中,因为如果我尝试通过任何REST客户端发送相同的请求,我都可以在Java代码中看到标头。

这是我的js代码:

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from './user.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

  constructor(private http: HttpClient, private userService: UserService) { }

  ngOnInit() {  
    this.userService.getAllUsers().subscribe(
      data => {
        console.log(data);
/*         this.users_from_db=data; */
      },
      err => {
        console.log(err);
      }
    );
  }

  users_from_db: Observable<any>;
}



import {Injectable} from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import {Observable} from 'rxjs/Observable';


const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class UserService {

  constructor(private http: HttpClient) {}

  public getAllUsers(): Observable<any> {
    return  this.http.get<any>('http://localhost:8080/users/get-all');
  }

}



import { Injectable } from '@angular/core';
import {HttpInterceptor, HttpRequest, HttpHandler, HttpSentEvent, HttpHeaderResponse, HttpProgressEvent,
  HttpResponse, HttpUserEvent, HttpErrorResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import {TokenStorage} from './token.storage';
import 'rxjs/add/operator/do';

const TOKEN_HEADER_KEY = 'Authorization';

@Injectable()
export class Interceptor implements HttpInterceptor {

  constructor(private token: TokenStorage, private router: Router) { }

  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {
    let authReq = req;
    if (this.token.getToken() != null) {
      console.log("authorizing...");
      authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + this.token.getToken())});
      console.log(authReq);
    }
    if (!authReq.headers.has('Content-Type')) {
      authReq = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
    }

    return next.handle(authReq).do(
        (err: any) => {
          if (err instanceof HttpErrorResponse) {
            console.log(err);
            console.log('req url :: ' + req.url);
            if (err.status === 401) {
              this.router.navigate(['login']);
            }
          }
        }
      );
  }

}

当我在拦截函数中执行this.token.getToken()时,令牌的值肯定存在。我通过在浏览器控制台中打印值进行检查。

感谢您的任何帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

这是我的拦截器:

import { Injectable } from "@angular/core";
import { HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse, HttpInterceptor } from "@angular/common/http";
import { Observable, BehaviorSubject, throwError } from "rxjs";
import { catchError, map, filter, take, switchMap, finalize } from "rxjs/operators";
import { AppConsts } from "../consts";

@Injectable()
export class JwtInterceptor implements HttpInterceptor {

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {        
        return next.handle(this.addTokenToRequest(request)).pipe(
            map(res => res),
            catchError(err => {
        if (err instanceof HttpErrorResponse && err.status === 401 && err.headers.has("Token-Expired")) {
                    // here code to refresh token if needed
                } else {
                    return throwError(err);
                }
            })
        );
    }

    private addTokenToRequest(request: HttpRequest<any>, token: string = null): HttpRequest<any> {
        if (token) {
            request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
        }
        else {
            const currentUser = JSON.parse(localStorage.getItem(AppConsts.DEFAULT_USER_STORAGE_NAME));
            if (currentUser && currentUser.token) {
                request = request.clone({
                    setHeaders: {
                        Authorization: `Bearer ${currentUser.token}`
                    }
                });
            }
        }
        return request;
    }
}

您还可以看到一个简单的示例-http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial