5

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

Neeraj Rathod
  • 1,385
  • 4
  • 12
  • 23
  • 1
    Looks like a CORS issue and something you will either need to configure on the server or something in the headers which is not quite right. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS – mbx-mbx Nov 28 '16 at 08:41
  • 1
    Yes, I do feel same but not getting the solution for that, any suggestion ? – Neeraj Rathod Nov 28 '16 at 10:20
  • @NeerajRathod, have you fixed it and working fine? I am troubleshooting the same thing. I am trying to create login and registration functionality with cakephp 3.4.0 and Angular 2. Could you please help me out? – mageDev0688 Jul 14 '17 at 11:05

1 Answers1

2

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?

Community
  • 1
  • 1
Vladimir M
  • 3,972
  • 1
  • 15
  • 21
  • Hi Vladimir M, I have tried with "Content-type :application/x-www-form-urlencoded" but it is not working, any other suggestion ? – Neeraj Rathod Nov 28 '16 at 10:19
  • does it still send options request? You might also want to remove "accept" header from the request, if options are still sent. – Vladimir M Nov 28 '16 at 10:52
  • No, I have removed options and pass headers object with 'Content-Type', 'application/x-www-form-urlencoded'. – Neeraj Rathod Nov 28 '16 at 10:57
  • can you update with the latest screen shot of that response from dev tools. – Vladimir M Nov 28 '16 at 11:40
  • I have put latest screen shot of response, please go through it and share some suggestion waiting – Neeraj Rathod Nov 28 '16 at 12:22
  • I think that now your auth data is still json and server expects url-encoded form. In this blog there is an example of a post construction: [link](https://auth0.com/blog/angular-2-series-part-3-using-http/) – Vladimir M Nov 28 '16 at 12:34
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/129238/discussion-between-neeraj-rathod-and-vladimir-m). – Neeraj Rathod Nov 28 '16 at 12:39