I am new to Angular 6, and I am having one issue with custom header for Authorisation. I am setting a Oauth2 token in Authorisation header but it is not going along with request. I have done a lot of googling but none of the solution solves my problem. Below I am adding code.
Custom header in request:
getCurrentUser() {
let token = this.cookie.get('token');
return this.http.get<User[]>(serverurl + 'getUser',{
headers: new HttpHeaders().set('Authorization', token),
}) // this.httpOptions
.pipe(
tap(user => this.log(`fetched current user`)),
catchError(this.handleError('currentUser', []))
);
}
As request Interceptor:
import { AuthService } from '../services/auth.service';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { CookieService } from 'ngx-cookie-service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthService, private cookie: CookieService) { }
intercept(req: HttpRequest<any>, next: HttpHandler) {
let token = this.cookie.get('token');
let changedRequest = req;
// HttpHeader object immutable - copy values
const headerSettings: { [name: string]: string | string[]; } = {};
if (token) {
headerSettings['Authorization'] = 'Bearer ' + token;
}
// headerSettings['Content-Type'] = 'application/json';
const newHeader = new HttpHeaders(headerSettings);
changedRequest = req.clone({
headers: newHeader
});
return next.handle(changedRequest);
}
}
It gives following request:
Authorisation token is added in Access-control-request-Header
instead of Authorisation
itself. And I don't see Authorisation header in request.
Thanks in Advance...!
After searching a lot for this I found the solution for this:
There is no problem in the code, since you are using Cross Origin
request it first sent OPTIONS
request to the server. In order to fix this I added following piece of code in my server configuration section:
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
It has nothing to do with Angular 6. Basically you need to Allow OPTIONS method for all URLs from server side. And it will work. :)