Practical Guide to Adding Authorization Headers and Configuring CORS in Angular and Go API Integration

Dec 04, 2025 · Programming · 10 views · 7.8

Keywords: Angular | Go | CORS | HTTP Interceptor | Authorization Header

Abstract: This article provides an in-depth exploration of how to correctly add authorization headers and resolve CORS preflight request issues when integrating Angular frontends with Go backend APIs. Through analysis of real-world development cases, it details the implementation of Angular HTTP interceptors, best practices for Go CORS configuration, and debugging techniques for cross-origin authentication. Based on high-scoring Stack Overflow answers with supplementary approaches, it offers comprehensive technical guidance.

Problem Background and Error Analysis

In the integration of Angular with Go APIs, developers often encounter Cross-Origin Resource Sharing (CORS) issues, especially when adding custom HTTP headers. According to the provided Q&A data, when an Angular application attempts to send a GET request with an Authorization header to a Go API, the browser triggers a preflight (OPTIONS) request. If the backend is not properly configured for CORS, it returns a 403 error, indicating No 'Access-Control-Allow-Origin' header is present on the requested resource.

Angular-Side Solution: HTTP Interceptors

In Angular 4 and above, it is recommended to use HTTP interceptors (HttpInterceptor) to uniformly manage request headers. Interceptors allow automatic addition of authentication information before requests are sent, avoiding repetitive configuration in each HTTP call. Here is a complete example of an AuthInterceptor implementation:

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);
  }
}

This interceptor modifies the original request using the req.clone() method to add standardized headers, including the Authorization header (using Bearer token format). It must be registered in 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,
    },
    ...
],

This approach ensures that all HTTP requests automatically include authentication headers, improving code maintainability and security.

Go Backend CORS Configuration Optimization

When using the gorilla/handlers library for CORS in Go, it is essential to ensure that allowed headers match those sent by the frontend. In the original configuration:

headersOk := handlers.AllowedHeaders([]string{"X-Requested-With, Content-Type, Authorization"});
originsOk := handlers.AllowedOrigins([]string{"*"});
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"});

The headersOk configuration may be problematic because AllowedHeaders expects a slice of strings where each element is a separate header name, not a comma-separated string. The correct approach is:

headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"});

Alternatively, for debugging purposes, all headers can be temporarily allowed:

headersOk := handlers.AllowedHeaders([]string{"*"});

This helps quickly verify if header matching is the issue. Once resolved, the configuration should be gradually refined to allow only necessary headers to enhance security.

Supplementary Approaches and Considerations

Besides interceptors, headers can be added directly in each HTTP request in Angular, as shown in supplementary answers:

var header = {
  headers: new HttpHeaders()
    .set('Authorization',  `Bearer ${AuthService.getToken()}`)
};
this.http.get(url, header);

However, this method can lead to code redundancy in large applications and is less maintainable. For Bearer tokens, ensure the correct format is used; for Basic authentication, btoa() encoding can be applied.

During debugging, using browser developer tools to inspect request and response headers is crucial. For example, the preflight request's Access-Control-Request-Headers should include authorization, and the backend response must include Access-Control-Allow-Headers: authorization.

Summary and Best Practices

When integrating Angular with Go APIs, the following steps are recommended: use HTTP interceptors in Angular to uniformly add authentication headers; configure CORS correctly in Go using gorilla/handlers, ensuring allowed headers, origins, and methods match frontend requests; and balance functionality with security through gradual debugging and refinement. This approach not only resolves CORS issues but also enhances the overall architecture quality of the application.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.