Home >Backend Development >Golang >How to Secure Angular-Go API Communication: Adding Authorization Headers?

How to Secure Angular-Go API Communication: Adding Authorization Headers?

Susan Sarandon
Susan SarandonOriginal
2024-12-16 04:13:17682browse

How to Secure Angular-Go API Communication:  Adding Authorization Headers?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn