Angular 2 Basic Authentication not working
Simplified version to add custom headers to your request:
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
@Injectable()
export class ApiService {
constructor(private _http: Http) {}
call(url): Observable<any> {
let username: string = 'username';
let password: string = 'password';
let headers: Headers = new Headers();
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
headers.append("Content-Type", "application/x-www-form-urlencoded");
return this._http.post(url, data, {headers: headers})
}
}
It's hard to determine where you went wrong, because the lack of code of the actual http
call you do. But this example should work for you
jrcastillo suggested another option here
I spent so many hours trying to fix this and this one liner solved my problem.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
}
I was a bit more specific in the end as this effected my /login path so I did the following instead:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/api/**");
}
I had same problem in my application.
As you can see the request that is sended is not POST but OPTION ( pre verification)
https://developer.mozilla.org/fr/docs/HTTP/Access_control_CORS
You must allowed the OPTIONS request at your API side. If you have Spring application you can just add this to Spring Security configuration :
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
**.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()**
(..)
}
In my case it works