This is my first post.
I\'ve just started learning Go and Angular and I\'m attempting to connect the angular app to a go api. I\'ve written both and am stuck identi
In case you don't want to add interceptor, this worked for me:
var header = {
headers: new HttpHeaders()
.set('Authorization', `Basic ${btoa(AuthService.getToken())}`)
}
this.http.get(url, header)
For Bearer,
set('Authorization', `Bearer ${AuthService.getToken()}`)
Angular 6 ==> HTTP Get request example with Authorization Header
public IsClientCreditCardExits(companyId: string, token: any) {
let header = new Headers({ 'Authorization': `Bearer ${token}` });
const options = new RequestOptions({
headers: header,
});
return this._http.get(this.ApiURL + "api/Subscriptions/IsClientCreditCardExits/" + companyId + "/", options);
}
Regarding the best way of handling Authentication headers in Angular > 4 it's best to use
Http Interceptors
for adding them to each request, and afterwards using
Guards
for protecting your routes.
Here's a full example of an AuthInterceptor
that I'm using in my app:
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);
}
}
You'll need to register your interceptor in the app.module
as a provider:
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,
},
...
],
...
You can read about this method further in this post.
Regarding the Go's side of things, this is most likely a case of mismatch between
Request Headers you're sending and the headers CORS allow.
First thing you should try is allowing all of them:
headersOk := handlers.AllowedHeaders([]string{"*"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
And if the problem goes away try carefully structuring your CORS one by one to what your client is sending.
Here is an example:
this.http
.get(url, return new RequestOptions({
headers: new Headers({
Authorization: `Bearer ${authtoken}`
}),
}))
.map(res => res.json());
The following example would fit a situation where you only want some headers added only when accessing resources that require authorization see code below. Kindly note that you need create the getToken method in your authentication.service.ts.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
import { AuthenticationService } from '../services/authentication.service';
@Injectable({
providedIn: 'root'
})
export class AuthenticationInterceptorService implements HttpInterceptor {
constructor(public authenticationService: AuthenticationService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const accessToken: string = this.authenticationService.getToken();
// set global application headers.
request = request.clone({
setHeaders: {
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json',
'X-AppName': environment.xAppName,
'X-Locale': 'en'
}
});
// Set headers for requests that require authorization.
if (accessToken) {
const authenticatedRequest = request.clone({
headers: request.headers.set(
'Authorization',
`Token token=${accessToken}`
)
});
// Request with authorization headers
return next.handle(authenticatedRequest);
} else {
// Request without authorization header
return next.handle(request);
}
}
}
Register the interceptor in app.module.ts as show below:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AuthenticationInterceptorService } from './services/authentication-interceptor.service';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, AppRoutingModule, HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthenticationInterceptorService,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}