Your cart is currently empty!
Angular 19 OAUTH2 bearer token interceptor example. (NswagStudio compatible 😎)
In this article, we’ll explore how to set up an auth interceptor in Angular to automatically add an authorization header to all outgoing HTTP requests. We’ll also discuss how to avoid modifying the generated api.ts
file after each API change.
Step 1: Set Up the Auth Interceptor
First, let’s create the auth interceptor. In the auth.interceptor.ts
file, we’ll import the necessary dependencies:
import { HttpInterceptorFn } from "@angular/common/http";
import { OAuthService } from 'angular-oauth2-oidc';
import { inject } from '@angular/core';
Next, we’ll define the authInterceptor
function:
export const authInterceptor: HttpInterceptorFn = (req, next) => {
// Use Angular's inject() function to get the OAuthService
const oAuthService = inject(OAuthService);
const token = oAuthService.getAccessToken();
if (token) {
const cloned = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
});
return next(cloned);
}
return next(req);
};
This interceptor checks if there is an access token available from the OAuthService
, and if so, it adds the token to the Authorization
header of the request.
Step 2: Provide the Interceptor
Next, we need to provide the interceptor in the main.ts
file. We’ll import the necessary dependencies:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { RouterModule, provideRouter } from '@angular/router';
import { AppComponent } from './app/app.component';
import { provideOAuthClient } from 'angular-oauth2-oidc';
import { routes } from './app/app.routes';
import { environment } from './app/environments/environment';
import { API_BASE_URL } from './app/api/api';
import { authInterceptor } from './app/auth/auth.interceptor';
Then, in the bootstrapApplication
function, we’ll add the authInterceptor
to the list of interceptors:
typescriptCopyInsertbootstrapApplication(AppComponent, {
providers: [
provideRouter(routes),
provideOAuthClient(),
provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
{ provide: API_BASE_URL, useValue: environment.baseUrl }
]
})
.catch(err => console.error(err));
By adding the auth interceptor to the HttpClient
instance, we can automatically add the authorization header to all outgoing HTTP requests without modifying the generated api.ts
file.
This approach has several benefits:
- We don’t need to modify the generatedÂ
api.ts
 file, which can be a hassle to maintain. - We can easily switch between different authentication mechanisms by changing the interceptor.
- We can add additional logic to the interceptor to handle errors or other edge cases.
Overall, using an auth interceptor is a great way to simplify authentication in Angular applications.
Leave a Reply