Angular 5通过拦截器在标头中设置Bearer标记

时间:2018-03-07 13:27:40

标签: asp.net-web-api2 angular5

拦截器在标头请求中设置承载令牌, Asp.net WebApi它没有显示标题。

app.modules.ts

    import { HTTP_INTERCEPTORS } from '@angular/common/http';
    import { TokenInterceptor } from './auth/token.interceptor';
    import { MainService } from './services/main.service';

    providers: [{ 
      provide: HTTP_INTERCEPTORS, 
      useClass: TokenInterceptor, 
      multi: true 
   }, MainService],

token.interceptor.ts

import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse, HttpErrorResponse  } from "@angular/common/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';

import { MainService } from '../services/main.service';
import { Router } from '@angular/router';

@Injectable()
export class  TokenInterceptor implements HttpInterceptor {

  _mainService: any;
  constructor(private injector: Injector, private _router: Router) { }

  intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
     this._mainService = this.injector.get(MainService);


    if(req.url.endsWith("/token") && req.method === "POST") 
    {
        // Login method
        return next.handle(req);
    }
    else 
    {
        const token: string = this._mainService.getToken();

        if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

        if (token) {
            req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
        }

        return next.handle(req);
    }
}

}

我在Asp.net Webapi中请求输出显示如下图像。

Output in image

1 个答案:

答案 0 :(得分:0)

在您使用本地主机的情况下,您遇到“ CORS”问题,因此请确保服务器中的 Access-Control-Allow-Headers 允许授权

>
Access-Control-Allow-Headers: Authorization

请参阅similar issue 可能对您有帮助