Home >Backend Development >Golang >How to Secure Angular HTTP Requests and Handle CORS in Go?
Handling Authorization Headers in Angular and Go
To add an Authorization header to Angular HTTP requests, consider utilizing HTTP Interceptors. They allow you to add headers to each request, while Guards can be used for route protection.
Angular HTTP Interceptor Example:
// auth.interceptor.ts import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { AuthService } from './auth.service'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { req = req.clone({ setHeaders: { 'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json', 'Authorization': `Bearer ${AuthService.getToken()}`, }, }); return next.handle(req); } }
Register the interceptor as a provider in app.module.ts:
// app.module.ts import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; import { AuthInterceptor } from '../auth/auth.interceptor'; ... imports: [ HttpClientModule, ... ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, }, ... ], ...
Go CORS Configuration:
In Go, ensure that your CORS configuration matches the HTTP headers sent by the client. If necessary, allow all headers:
headersOk := handlers.AllowedHeaders([]string{"*"}) originsOk := handlers.AllowedOrigins([]string{"*"}) methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
Inspect the headers in your Chrome Developer Tools and consider carefully reconfiguring your CORS settings to align with the client's headers. This will resolve the CORS issues you're experiencing.
The above is the detailed content of How to Secure Angular HTTP Requests and Handle CORS in Go?. For more information, please follow other related articles on the PHP Chinese website!