Commit 0669d39a authored by Almouhannad's avatar Almouhannad

(F) Add authentication interceptor

parent ba98801b
......@@ -13,8 +13,10 @@ import { FooterComponent } from './components/template/footer/footer.component';
import { HomeComponent } from './components/home/home.component';
import { LoginFormComponent } from './components/Authentication/login-form/login-form.component';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { AuthenticationService } from './services/authentication/authentication.service';
import { AuthenticationInterceptor } from './services/authentication/interceptor/authentication.interceptor';
@NgModule({
imports: [
......@@ -32,6 +34,7 @@ import { AuthenticationService } from './services/authentication/authentication.
// all parts of the app
providers: [
AuthenticationService,
{ provide: HTTP_INTERCEPTORS, useClass: AuthenticationInterceptor, multi: true},
],
// components and directives that belong to this module
......
......@@ -23,19 +23,12 @@ export class AuthenticationService {
private readonly USERS_ENDPOINT: string = `${config.apiUrl}/Users`
//#region HTTP headers
private readonly HTTP_HEADERS: HttpHeaders = this.getHeaders();
getHeaders(): HttpHeaders {
return new HttpHeaders().set('Content-Type', 'application/json');
}
//#endregion
//#endregion
//#region Login
private postLogin(loginCommand: LoginCommand): Observable<LoginResponse> {
return this.http.post<LoginResponse>(
this.USERS_ENDPOINT, loginCommand, { headers: this.HTTP_HEADERS });
this.USERS_ENDPOINT, loginCommand);
}
login(loginCommand: LoginCommand): Observable<LoginResult> {
......
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpHeaders } from '@angular/common/http';
import { JWTHandler } from '../jwtHandler';
import { Observable } from 'rxjs';
@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {
//#region HTTP headers
private readonly HTTP_HEADERS: HttpHeaders = this.getHeaders();
getHeaders(): HttpHeaders {
return new HttpHeaders().set('Content-Type', 'application/json');
}
//#endregion
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const jwt = JWTHandler.getJwtFromCookie();
console.log(req);
req = req.clone({
headers: this.HTTP_HEADERS
});
if (jwt !== null) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${jwt}`
}
});
}
console.log(req);
return next.handle(req);
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment