Mudanças entre as edições de "Example of Http Interceptor for login authentication"

De Basef
Ir para: navegação, pesquisa
 
(3 revisões intermediárias pelo mesmo usuário não estão sendo mostradas)
Linha 1: Linha 1:
Example of Interceptor for login authentication:
+
An Http Interceptor can be used to verify if the user is logged in or to inject http headers to every http request.
 +
 
 +
In the example above, we are injecting a Authorization http header to every request:
  
 
'''auth-interceptor.js'''
 
'''auth-interceptor.js'''
Linha 31: Linha 33:
  
 
'''In your module:'''
 
'''In your module:'''
<source lang="">
+
<source lang="javascript">
 +
 
 +
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
 +
import { AuthInterceptor } from "./login/auth.interceptor";
 +
 
 +
@NgModule({
 +
  ...
 
   providers: [
 
   providers: [
 
     ...
 
     ...
Linha 41: Linha 49:
 
     ...
 
     ...
 
   ]
 
   ]
 +
  ...
 +
})
 +
 
</source>
 
</source>
  
[[Category: AngularJS2]]
+
[[Category: Angular]]

Edição atual tal como às 09h38min de 27 de janeiro de 2020

An Http Interceptor can be used to verify if the user is logged in or to inject http headers to every http request.

In the example above, we are injecting a Authorization http header to every request:

auth-interceptor.js

import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { LoginService } from './login.service';
 
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
 
  constructor(private injector: Injector) {
 
  }
 
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const loginService = this.injector.get(LoginService);
 
    if (loginService.isLoggedIn()) {
      const authRequest = request.clone(
        { setHeaders:{'Authorization': `Bearer ${loginService.getUser().accessToken}`}});
 
      return next.handle(authRequest);
    } else {
      return next.handle(request);
    }
  }
}

In your module:

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { AuthInterceptor } from "./login/auth.interceptor";
 
@NgModule({
  ...
  providers: [
    ...
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi: true
    },
    ...
  ]
  ...
})