拦截器未设置授权令牌 [英] Interceptor not setting the authorization token

查看:22
本文介绍了拦截器未设置授权令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi I'm trying to write a simple Angular 6 interceptor that adds the jwt token to the header when sending requests.

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

The problem is that the header in the request arrives NULL on the backend, so of course I can't get the authorization token and I'm having trouble figuring out why.

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

I'm pretty sure the problem is in my js code because if I try to send the same request via any REST client I can see the header in my Java code just fine.

这是我的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() 时,令牌的值肯定存在.我通过在浏览器控制台中打印值来进行检查.

The value of the token is surely there when I do this.token.getToken()in the intercept function. I checked by printing the value in the browser console.

感谢任何帮助,谢谢.

推荐答案

这是我的拦截器:

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

You also can see a simple example - http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial

这篇关于拦截器未设置授权令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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