删除某些http调用Angular的授权标头

问题描述 投票:1回答:2

我对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);
        }
    }

home-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
2个回答
0
投票

您可以使用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);
  }

0
投票

更确切地说,您可以看下面的示例

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;
    }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.