I am using Angular 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 Angular.
Here is my TypeScript 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
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With