Neeraj Rathod Neeraj Rathod - 7 days ago 5
AngularJS Question

Getting 401 Unauthorized on Post method [ Front end - Angularjs 2 & Back end - Cakephp 3]

I am using Angularjs 2 for Front end & Back end in Cakephp 3. I am getting 401 Unauthorized status while I am trying to login. I have configured JWT in cakephp 3 and it is working fine in POSTMAN. But not working with angularjs 2.

Here is my angularjs 2 code

loginToken(uname: string, pwd: string): Observable<boolean>{
let json = JSON.stringify({ username: uname , password: pwd});
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });

return this.http.post('http://localhost/crm/crm/api/users/token', json, options)
.map((response: Response) => {
let token = response.json() && response.json().token;
if (token) {
this.token = token;
localStorage.setItem('currentUser'
, JSON.stringify({ username: uname, token: token }));
return true;
} else {
return false;
}
});
}


Cakephp 3 code - server side

public function token()
{
$user = $this->Auth->identify();
if (!$user) {
throw new UnauthorizedException('Invalid username or password');
}

$this->set([
'success' => true,
'data' => [
'token' => JWT::encode([
'sub' => $user['id'],
'exp' => time() + 604800
],
Security::salt())
],
'_serialize' => ['success', 'data']
]);

}


Here are some screenshots
enter image description here

enter image description here

enter image description here
Please help me out on this.

After removing options -

loginToken(uname: string, pwd: string): Observable<boolean>{
let json = JSON.stringify({ username: uname , password: pwd});
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });

return this.http.post('http://localhost/crm/crm/api/users/token', json, {headers: headers })
.map((response: Response) => {
let token = response.json() && response.json().token;
if (token) {
this.token = token;
localStorage.setItem('currentUser'
, JSON.stringify({ username: uname, token: token }));
return true;
} else {
return false;
}
});
}


and response I got

enter image description here

enter image description here

Answer

Your problem is missing or wrong content type header.

For login not to send OPTIONS requests your content type should be one of the standard form types: application/x-www-form-urlencoded or multipart/form-data

I think, text/pain might also work, but I didn't use it myself.

EDIT: actually there is a SO about it: How to disable OPTIONS request?

Comments