I am new to Angular2.
My backend server has "Spring Security" implemented. User needs to send username & Password for LDAP Authentication .
In reference to : Angular2 - set headers for every request
This is how i am trying :
login(username:string,password:string) {
let headers = new Headers();
this.createAuthorizationHeader(headers,username,password);
return this.http.get(this.url,headers).map(this.extractData)
.catch(this.handleError).subscribe(e=>console.log(e));
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
createAuthorizationHeader(headers:Headers,username:string,password:string) {
headers.append("Authorization", "Basic " + btoa(username + ":" + password));
headers.append("x-requested-with", 'XMLHttpRequest');
}
but i get 401 , but my credentials are correct. When i try them using Rest client it works perfectly fine.
I checked on server logs, request is reaching there but unfortunately not much information from there.
When i debug on frontend side, i see valid value in Authorization header (encrypted) before request being fired.
UPDATE
Productive code (Angular1):
In Angular1 it is implemented like this :
function logIn(username, password, callback) {
var token = "Basic " + btoa(username + ":" + password);
authenticate(token, callback);
} function authenticate(token, callback) {
if(token.indexOf('Basic') > -1) {
var headers = {
Authorization: token,
"x-requested-with": 'XMLHttpRequest'
};
var url = ConfigService.getConfig("backend").url;
return this.$http({
method: "GET",
url: url + "login",
withCredentials: true,
headers: headers
}).then(function (success) {
$log.debug("AuthService.successfully logged in.");
var user = success.data;
user.auth = headers.Authorization;
$http.defaults.headers.common.Authorization = user.auth;
setUserInfo(
user,
new Date().getDate() + expireTime);
callback(success);
}, function (error) {
if(error.status === -1) {
ToastService.showError('There seems to be a CORS problem. Do you use the right server?', error);
} else {
ToastService.showError(error.statusText, error);
$log.error('credentials must be wrong.');
}
$log.error(error);
});
}
}
I dont see any difference between my implementation and production code. Please help with this.
Thanks