Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 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

like image 844
Neeraj Rathod Avatar asked Oct 30 '22 16:10

Neeraj Rathod


1 Answers

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?

like image 170
Vladimir M Avatar answered Nov 15 '22 06:11

Vladimir M