【问题标题】:Remove Authorization Header for some http calls Angular删除某些 http 调用 Angular 的授权标头
【发布时间】:2020-02-11 02:17:35
【问题描述】:

我是 Angular 新手,正在尝试设置 HTTP 授权标头。到目前为止,如果令牌有效,我可以为所有 API 设置授权标头。我想要的是仅在令牌可用的情况下为某些 API 设置标头。

app.module.ts

@NgModule({
  declarations: [AppComponent],
  imports: [
    HttpClientModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
  ]
})

jwt.interceptor.ts

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';

    import { AuthenticationService } from '@/_services';
    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs';

    @Injectable()
    export class JwtInterceptor implements HttpInterceptor {
        constructor(private authenticationService: AuthenticationService) {}

        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            // add authorization header with jwt token if available
            const currentUser = this.authenticationService.currentUserValue;
            if (currentUser && currentUser.token) {
                request = request.clone({
                    setHeaders: {
                        Authorization: `Bearer ${currentUser.token}`
                    }
                });
            }

            return next.handle(request);
        }
    }

主页-http.service.ts

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

@Injectable()
export class HomeHttpService {
    constructor(private http: HttpClient) { }

    getAll(url: string, paramsVal?: any): Observable<any[]> {
        const options = {params: paramsVal};
        return this.http.get<any[]>(url, options);
    }

    public getByID(url: string, id: number | string): Observable<any> {
        return this.http.get<any>(`${url}/${id}`);
    }

    public delete(url: string): Observable<any> {
        return this.http.delete<any>(url).pipe(
            map(response => {
                return response;
            })
        );
    }

    public post(data = [], url: string): Observable<any> {
        return this.http.post<any>(url, data);
    }

    public getExternal(url: string): Observable<any> {
        return this.http.get<any>(url);
    }

    public put(data: any, url: string): Observable<any> {
        return this.http.put<any>(url, data);
    }
}

home.service.ts

import { Injectable } from '@angular/core';

import { HomeHttpService } from '../home-http.service';
import { Observable } from 'rxjs';

@Injectable()
export class HomePageService {
  constructor(private apiservice: HomeHttpService) {}
  private basePath = `${url}`;

getAlldata(data): Observable<any> {
    return this.apiservice.getAll(this.basePath, data);
  }

如何设置我的代码,以便对于某些 API,我可以删除某些 API 的授权标头

【问题讨论】:

  • 请告诉我在否决之前我可以做些什么来改善我的问题

标签: angular angular-http-interceptors


【解决方案1】:

您可以使用request.url 属性来过滤您需要的内容。 最简单的方法之一:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // add authorization header with jwt token if available
    const currentUser = this.authenticationService.currentUserValue;
    if (request.url.indexOf('some APIs path') === 0 && currentUser && currentUser.token) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${currentUser.token}`
        }
      });
    }

    return next.handle(request);
  }

【讨论】:

  • 你能详细说明或举例吗
  • 最简单的方法之一:intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; { // add authorization header with jwt token if available const currentUser = this.authenticationService.currentUserValue; if (request.url.indexOf('some APIs path') === 0 &amp;&amp; currentUser &amp;&amp; currentUser.token) { request = request.clone({ setHeaders: { Authorization: `Bearer ${currentUser.token}` } }); } return next.handle(request); }
  • 这看起来不像标准解决方案。
【解决方案2】:

更准确地说,你可以看看下面的例子

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';

import { AuthenticationService } from '@/_services';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        const currentUser = this.authenticationService.currentUserValue;
        if (this.isHeaderNeeded() &&currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
        }

        return next.handle(request);
    }
}

isHeaderNeeded(url: string) {
    if (url === "other.api.com") { // this condition is up to you, it could be an exact match or how ever you like
        return false;
    } else {
        return true;
    }
}

【讨论】:

    【解决方案3】:

    在那些服务文件中使用这种方式

    import {HttpBackend, HttpClient} from "@angular/common/http";
    
    constructor(private http: HttpClient, handler: HttpBackend ) {
        this.http = new HttpClient(handler);
    }
    

    【讨论】:

    • 最简单的办法就是最好的办法
    • 不需要注入httpClient,可以从构造函数中去掉,作为字段包含:http:HttpClient;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2016-05-25
    • 2011-06-08
    • 2018-03-21
    • 2016-09-06
    • 2015-11-07
    • 2015-05-30
    相关资源
    最近更新 更多