mercredi 26 décembre 2018

Laravel 5.7 with Tymon JWTAuth and Angular 7 get always "invalid_credentials"

I'm using Laravel 5.7 with Tymon\JWTAuth in backend and Angular 7 on frontend. I use this PHP code:

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');
    try {
        // attempt to verify the credentials and create a token for the user
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        // something went wrong whilst attempting to encode the token
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    // all good so return the token
    return response()->json(compact('token'));
}

This code is from original documentation of Tymon's JWTAuth documentation as example code.

I was created an instance in Postman to test this code with these options:

Headers:

Content-Type: application/json

Body:

{
    "email": "admin@admin.test",
    "password": "admin"
}

Everytinghs working fine. I get back a token in the right format like this:

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ey....EifQ.nMr5Q1mX9O-3dknpNRBjOiOc1QJjEJydaOJOVqNFfWc"
}

And then I try to use in Angular with this code:

export class AuthService {

  constructor(private http: Http) { }

  login(credentials: any) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');

    const options = new RequestOptions({ headers: headers });

    return this.http.post(
        '/api/auth/login',
        JSON.stringify(credentials)
      )
      .pipe(map(response => {
        const result = response.json();

        if (result && result.token) {
          localStorage.setItem('token', result.token);
          return true;
        }

        return false;
      }));
  }

  // ...
}

And this get back this error message:

{_body: "{"error":"invalid_credentials"}", status: 401, ok: false, statusText: "Unauthorized", headers: Headers, ...}

The URL is checked, that is same in both case. The user and password is checked, that is same too in both case.

I have no clue what do I wrong in Angular. Any idea?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire