I am trying to get the authtoken from RestAPI using the below method. The same url,Params and Headers returns me proper response from postman. but in angular i am getting 401 unauthorized error. please help me understand where i am doing wrong? I am unable to understand why my headers are inside lazyUpdate object inside httpHeaders.
Thanks in advance.
login(loginData) {
const httpOptions = {
headers:new HttpHeaders().set("Authorization", "Basic " + btoa("username:password")).set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8").set("access-control-allow-credentials",'true'),
params:new HttpParams().set('username', loginData.email).set('password', loginData.password).set('grant_type', 'grant_type')
}
this.http.post('http://xx.xx.xx.xx:xxxxx/oauth/token', httpOptions).subscribe(
data => {
this.saveToken(data);
return true;
},
err => {
alert('Invalid Credentials')
return false;
});
}
Please find the attached screenshot of the headers being sent from browser.
Use the HTTP header option as a third parameter in the post request.
login(loginData) {
let httpOptions = {
headers: new HttpHeaders({
"Access-Control-Allow-Credentials": "true",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
'Authorization' : "Basic " + btoa("username:password"),
'username': loginData.email,
'password': loginData.password,
'grant_type': 'grant_type'
})
};
this.http.post('http://xx.xx.xx.xx:xxxxx/oauth/token', {}, httpOptions).subscribe( data => {
this.saveToken(data);
return true;
},
err => {
alert('Invalid Credentials')
return false;
});
}