最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting request with auth token via Angular Interceptor and Intercepting further calls - Stack Overflow

programmeradmin0浏览0评论

I'm trying to authenticate to an API first and then "attach" the token to each one of my requests, but the one including 'connect'. I have the following:

Interceptor

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (!request.url.includes('/connect/token?grant_type=client_credentials')) {
      this.authService.isTokenExist()
      .pipe(
        catchError((error) => {
          return error;
        })
      )
      .subscribe((token: any) => {
        if (token) {
          request = request.clone({
            setHeaders: {
              Authorization: `Bearer ${token}`,
            },
          });
        }
        return next.handle(request);
      });
    }
    return next.handle(request); // here I'm hitting the point without token and I think this is the problem
  }
}

Service

import { Injectable } from '@angular/core';
import {
  HttpClient,
  HttpHeaderResponse,
  HttpHeaders,
} from '@angular/common/http';
import { environment } from '../../../environment';
import { urlString } from '../../utils/helpers';
import { Observable, catchError, of } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor(private http: HttpClient) {}

  getToken(): Observable<string | null> {
    const requestBody: Request = {
      client_id: environment.client_id,
      client_secret: environment.client_secret,
      grant_type: environment.grant_type,
      scope: environment.scope,
    };
    const headers = new HttpHeaders().set(
      'Content-Type',
      'application/x-www-form-urlencoded'
    );
    const options = { headers };
    return this.http
      .post<Response>(
        `${environment.api_url}/connect/token?grant_type=client_credentials`,
        urlString(requestBody),
        options
      )
      .pipe(
        catchError((error) => {
          throw error;
        }),
        map((response: Response) => {
          this.setToken(response.access_token);
          return response.access_token;
        })
      );
  }

  getFileMetadata(fileId: number): Observable<any> {
    return this.http.get(
      `${environment.api_url}/api/v1.4/items/${fileId}/_metadata`
    );
  }

  isTokenExist(): Observable<string | null> {
    const tokenTime = localStorage.getItem('token_time');
    if (tokenTime) {
      const currentTime = new Date().getTime();
      const tokenTimeInt = parseInt(tokenTime, 10);
      if (currentTime - tokenTimeInt > 86400000) {
        return this.getToken();
      }
    } else {
      this.getToken().subscribe({
        next: (token) => {
          if (token) {
            this.setToken(token);
          }
          return of(token);
        },
        error: (error) => {
          throw error;
        }
      });
    }
    return of(localStorage.getItem('token'));
  }

  setToken(token: string): void {
    localStorage.setItem('token_', token);
    localStorage.setItem('token_time', new Date().getTime().toString());
  }
}

interface Request {
  grant_type: string;
  client_secret: string;
  client_id: string;
  scope: string;
}

interface Response {
  access_token: string;
  token_type: string;
  expires_in: number;
}

The result is that on the first-page load, I get 401, as the interceptor is just passing the request. The service returns the token on refresh, and the request passes as expected. My question is, how can we hold the Interceptor until the token is available and then intercept all other calls?

I'm trying to authenticate to an API first and then "attach" the token to each one of my requests, but the one including 'connect'. I have the following:

Interceptor

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (!request.url.includes('/connect/token?grant_type=client_credentials')) {
      this.authService.isTokenExist()
      .pipe(
        catchError((error) => {
          return error;
        })
      )
      .subscribe((token: any) => {
        if (token) {
          request = request.clone({
            setHeaders: {
              Authorization: `Bearer ${token}`,
            },
          });
        }
        return next.handle(request);
      });
    }
    return next.handle(request); // here I'm hitting the point without token and I think this is the problem
  }
}

Service

import { Injectable } from '@angular/core';
import {
  HttpClient,
  HttpHeaderResponse,
  HttpHeaders,
} from '@angular/common/http';
import { environment } from '../../../environment';
import { urlString } from '../../utils/helpers';
import { Observable, catchError, of } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor(private http: HttpClient) {}

  getToken(): Observable<string | null> {
    const requestBody: Request = {
      client_id: environment.client_id,
      client_secret: environment.client_secret,
      grant_type: environment.grant_type,
      scope: environment.scope,
    };
    const headers = new HttpHeaders().set(
      'Content-Type',
      'application/x-www-form-urlencoded'
    );
    const options = { headers };
    return this.http
      .post<Response>(
        `${environment.api_url}/connect/token?grant_type=client_credentials`,
        urlString(requestBody),
        options
      )
      .pipe(
        catchError((error) => {
          throw error;
        }),
        map((response: Response) => {
          this.setToken(response.access_token);
          return response.access_token;
        })
      );
  }

  getFileMetadata(fileId: number): Observable<any> {
    return this.http.get(
      `${environment.api_url}/api/v1.4/items/${fileId}/_metadata`
    );
  }

  isTokenExist(): Observable<string | null> {
    const tokenTime = localStorage.getItem('token_time');
    if (tokenTime) {
      const currentTime = new Date().getTime();
      const tokenTimeInt = parseInt(tokenTime, 10);
      if (currentTime - tokenTimeInt > 86400000) {
        return this.getToken();
      }
    } else {
      this.getToken().subscribe({
        next: (token) => {
          if (token) {
            this.setToken(token);
          }
          return of(token);
        },
        error: (error) => {
          throw error;
        }
      });
    }
    return of(localStorage.getItem('token'));
  }

  setToken(token: string): void {
    localStorage.setItem('token_', token);
    localStorage.setItem('token_time', new Date().getTime().toString());
  }
}

interface Request {
  grant_type: string;
  client_secret: string;
  client_id: string;
  scope: string;
}

interface Response {
  access_token: string;
  token_type: string;
  expires_in: number;
}

The result is that on the first-page load, I get 401, as the interceptor is just passing the request. The service returns the token on refresh, and the request passes as expected. My question is, how can we hold the Interceptor until the token is available and then intercept all other calls?

Share Improve this question asked Nov 18, 2024 at 11:05 VladynVladyn 5831 gold badge6 silver badges20 bronze badges 3
  • 1 Maybe you can use async / await? – Marco Commented Nov 20, 2024 at 5:01
  • 1 I've got a bit rusty with the latest Angular, but yes, you are right; it could be async imperative flavor. But I've read on the web that angular direction is more reactive. That's why I'm trying to follow it with RxJs. – Vladyn Commented Nov 20, 2024 at 8:33
  • I see, well I'm more experienced in Vue, but with vue-router you can conditionally user a middleware / interceptor to check if you need auth / token, maybe this is the way to go? – Marco Commented Nov 21, 2024 at 5:10
Add a comment  | 

2 Answers 2

Reset to default 1

One advice would be to take the token from local storage since your already set it there. Most probably you save it on login and should be available for every call you will do afterwards. You should not call an endpoint in interceptor. Interceptors are primarily designed to inspect and manipulate HTTP requests and responses globally, such as adding headers, logging, or handling errors.

Then in interceptor you can get your token and attach it to header

const token = localStorage.getItem(‘token’);
let headers = request.headers;
if (token) {
 headers = headers.set('Authorization', `Bearer ${token}`);
}
 const req = request.clone({ headers });

And then pass the new ‘req’ as your request.

I did this refactoring in the interceptor:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (request.url.includes('/connect/token?grant_type=client_credentials')) {
      return next.handle(request);
    }
    return this.authService.isTokenExist().pipe(
      catchError((error) => {
        throw error;
      }),
      switchMap((token: string) => {
        const headers = request.headers.set('Authorization', `Bearer ${token}`);
        const newRequest = request.clone({ headers });
        return next.handle(newRequest);
      })
    );
  }
}

...and in service, I changed methods like this:

import { Injectable } from '@angular/core';
import {
  HttpClient,
  HttpHeaderResponse,
  HttpHeaders,
} from '@angular/common/http';
import { environment } from '../../../environment';
import { urlString } from '../../utils/helpers';
import { Observable, catchError, of } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor(private http: HttpClient) {}

  getToken(): Observable<string> {
    const requestBody: Request = {
      client_id: environment.client_id,
      client_secret: environment.client_secret,
      grant_type: environment.grant_type,
      scope: environment.scope,
    };
    const headers = new HttpHeaders().set(
      'Content-Type',
      'application/x-www-form-urlencoded'
    );
    const options = { headers };
    return this.http
      .post<Response>(
        `${environment.api_url}/connect/token?grant_type=client_credentials`,
        urlString(requestBody),
        options
      )
      .pipe(
        catchError((error) => {
          throw error;
        }),
        map((response: Response) => {
          this.setToken(response.access_token);
          return response.access_token;
        })
      );
  }

  isTokenExist(): Observable<any> {
    const tokenTime = localStorage.getItem('token_time');
    const token = localStorage.getItem('token');
    if (tokenTime) {
      const currentTime = new Date().getTime();
      const tokenTimeInt = parseInt(tokenTime, 10);
      if (currentTime - tokenTimeInt > 86400000) {
        return this.getToken();
      }
    }

    if (!token) {
      return this.getToken();
    }

    return of(localStorage.getItem('token'));
  }

  setToken(token: string): void {
    localStorage.setItem('token', token);
    localStorage.setItem('token_time', new Date().getTime().toString());
  }

  getFileMetadata(fileId: number): Observable<any> {
    return this.http.get(
      `${environment.api_url}/api/v1.4/items/${fileId}/_metadata`
    );
  }

  getFileBlob(uniformName: string, path: string): Observable<Blob> {
    const currentPath = path.replace(/\\/g, '/');
    return this.http.get(
      `${environment.api_url}/content/v1.4/${currentPath}/${uniformName}/_blob`,
      { responseType: 'blob' }
    );
  }
}

interface Request {
  grant_type: string;
  client_secret: string;
  client_id: string;
  scope: string;
}

interface Response {
  access_token: string;
  token_type: string;
  expires_in: number;
}

Basically the refactoring is in the Interceptor intercept function:

...
if (request.url.includes('/connect/token?grant_type=client_credentials')) {
      return next.handle(request);
    }
    return this.authService.isTokenExist().pipe(
      catchError((error) => {
        throw error;
      }),
      switchMap((token: string) => {
        const headers = request.headers.set('Authorization', `Bearer ${token}`);
        const newRequest = request.clone({ headers });
        return next.handle(newRequest);
      })
    );
....

Where by using early return is the request isn't a one for token. There service further, I'm returning an Observable instead if a string or null and a bit more logic in the method `isTokeExist()'

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论