0 votes
in Angular by

Can you provide an example of how to implement a secure HTTP interceptor in Angular to add JWT to the request headers?

1 Answer

0 votes
by

To implement a secure HTTP interceptor in Angular for adding JWT to request headers, follow these steps:

1. Create an authentication service that handles token storage and retrieval.

2. Generate an interceptor class implementing HttpInterceptor.

3. In the intercept method, retrieve the JWT from the authentication service.

4. Clone the original HttpRequest object with modified headers containing the JWT.

5. Call next.handle() with the cloned request.

Example code:

// auth.service.ts

@Injectable()

export class AuthService {

getToken(): string { /* … */ }

}

// jwt.interceptor.ts

@Injectable()

export class JwtInterceptor implements HttpInterceptor {

constructor(private authService: AuthService) {}

intercept(req: HttpRequest, next: HttpHandler): Observable> {

const token = this.authService.getToken();

if (token) {

req = req.clone({ setHeaders: { Authorization: Bearer ${token} } });

}

return next.handle(req);

}

}

// app.module.ts

@NgModule({

providers: [

{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },

],

})

export class AppModule {}

Related questions

+1 vote
asked Sep 17, 2019 in BlockChain by abhijeet_kumar
0 votes
asked Aug 30, 2023 in Android Library by SakshiSharma
...