How to Add Authorization Header to Angular HTTP Requests
When attempting to connect an Angular application to a Go API, it's essential to include authorization headers in the HTTP requests. This secures the communication between the client and server. The following demonstrates how to accomplish this:
Angular Implementation:
In Angular 4 and above, it's recommended to use HTTP Interceptors to apply authorization headers consistently to requests. Here's an example of an interceptor:
import { Injectable } from '@angular/core'; import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { req = req.clone({ setHeaders: { Authorization: `Bearer ${AuthService.getToken()}`, }, }); return next.handle(req); } }
This interceptor can be registered in the Angular module:
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; ... providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, }, ], ...
Go Implementation:
In Go, CORS headers need to match the ones sent by the Angular application. To allow all headers, use the following:
headersOk := handlers.AllowedHeaders([]string{"*"}) originsOk := handlers.AllowedOrigins([]string{"*"}) methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
Alternatively, carefully define the headers permitted.
Once these steps have been taken, authorization headers should be successfully transmitted and accepted, enabling the communication between Angular and Go.
The above is the detailed content of How to Secure Angular-Go API Communication: Adding Authorization Headers?. For more information, please follow other related articles on the PHP Chinese website!