How to fix 401 (Unauthorized) for a login request

Viewed 2023

I'm getting a 401 error for my login requests using JWT authentication, on the signup page it's working great and it creates the user in database, but the login is not working. I really dunno which code to include so feel free to for the needed code.

I verified that entered credentials already exists in the database

login.ts

export class LoginComponent {

  public form={
em:null,
pass:null
  };
  public error = null;
    constructor(private http :HttpClient) { 

    }
Submit(){
    this.http.post('http://localhost:8000/api/login',this.form).subscribe(
      data => console.log(data),
      error => console.log(error)
    );

  }
    }

api.php

<?php


Route::group([

    'middleware' => 'api',


], function () {

    Route::post('login', 'AuthController@login');
});

login function

public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'user does not exist'], 401);
        }

        return $this->respondWithToken($token);
    }
1 Answers

You need to send an Authorization header in your post request:

Authorization: 'Bearer ' + jwtToken

Instead of sending the authorization header manually in each api call, better option is to use HttpInterceptor.

See this blog for more details

Related