I'm building a secure client portal and I'm looking for the most modern way to handle JWT authentication. Should I still be using HttpInterceptors for attaching tokens, or is there a more "functional" way to do this now? Also, with the deprecation of certain routing guards, what is the recommended way to protect routes and handle redirects if the user's session expires? I want to ensure I'm following 2024 security standards.
3 answers
In Angular 18, you should definitely move toward functional interceptors. Instead of the old class-based approach, you can define your interceptor as a simple function and provide it in your app.config.ts using withInterceptors([authInterceptor]). For route protection, the "Class-based Guards" are indeed deprecated; you should use "Functional Guards" now. They are much easier to test and can be defined right in your route configuration. For session expiry, I usually combine an interceptor to catch 401 errors with a central AuthService that triggers a redirect to the login page.
Comment: You use the inject() function, William! Since functional interceptors run within an injection context, you can just call const authService = inject(AuthService); at the top of your function. It’s actually much cleaner than the old constructor-based DI and makes the code a lot more readable. This pattern is being used everywhere in modern Angular, including inside components and pipes.
Don't forget to use canActivate: [() => inject(AuthService).isLoggedIn()] for your routes. It's the standard functional way to protect components.
Exactly! Functional guards like the one Joseph mentioned are so much more concise. No more creating a whole file just for a simple true/false check.
You use the inject() function, William! Since functional interceptors run within an injection context, you can just call const authService = inject(AuthService); at the top of your function. It’s actually much cleaner than the old constructor-based DI and makes the code a lot more readable. This pattern is being used everywhere in modern Angular, including inside components and pipes.