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
Release: 2024-12-16 04:13:17
Original
688 people have browsed it

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);
  }
}
Copy after login

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,
    },
],
...
Copy after login

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"})
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template