Search code examples
angularhttpservertokenangular8

Angular access with token


in angular: I have to sent [access_token_value] to each function who access to server. can I do it global?

I mean that I do not want to add it for each function ,but write it once

can i do it?

Thanks!!


Solution

  • You need to use Interceptors. Read about them here in the Angular Official Documentation..

    Here is an example I attach to help you understand how to create one and pass the token to it.

    import {
      HttpEvent,
      HttpHandler,
      HttpHeaders,
      HttpInterceptor,
      HttpRequest,
    } from '@angular/common/http'
    import { Injectable } from '@angular/core'
    import { Observable } from 'rxjs'
    
    @Injectable()
    export class AuthHttpInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token = localStorage.getItem('access_token') // <--- stored token to be passed to interceptor request headers
        if (token) {
          const authRequest = req.clone({
            setHeaders: {
              'Content-Type': 'application/json',
              Authorization: `Bearer ${token}`, // <---- your token goes here
            },
          })
          return next.handle(authRequest)
        } else {
          const headers = new HttpHeaders({
            'Content-Type': 'application/json',
          })
          const cloned = req.clone({
            headers,
          })
          return next.handle(cloned)
        }
      }
    }