Search code examples
reactjslaravel-passport

401 unauthorized error when accessing protected controller, using passport and axios


I am using laravel 5.8 with preset react. Currently I am trying to workout authentication also I decided to use passport in backend and axios in fronend however I am getting this error when making axios request to protected controller AdminController@index

GET http://localhost:8000/api/admin/index 401 (Unauthorized)

I expected not to get it because I think I authenticated the user

I followed laravel passport instalation guide and now I am able to register, login user and get it's access token, but it seems that user logs out on new axios request because I get 401 error. Here is some context

in middleware I added this line


protected $middleware = [
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
]

//in AuthServiceProvider I added this and added Carbon because of error
Passport::routes(function ($router) {
            $router->forAccessTokens();
            $router->forPersonalAccessTokens();
            $router->forTransientTokens();
        });

        Passport::tokensExpireIn(Carbon::now()->addMinutes(10));

        Passport::refreshTokensExpireIn(Carbon::now()->addDays(10));

        Passport::cookie('user_data');

In users model I added


use Notifiable, HasApiTokens;
//and
protected $primaryKey = 'id';

changed auth:api driver to passport

'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
        ],

this is my migration table


Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

This is my login and register almost the same axios request

        var bodyFormData = new FormData;
        bodyFormData.append('name', this.state.name);
        bodyFormData.append('password', this.state.password);
        axios({
            method: 'post',
            url: '/api/login',
            data: bodyFormData,
            config: { headers: {'Content-Type': 'multipart/form-data' }}
        })
            .then(function (response) {
                if(response.data.auth){
                    var cookies = new Cookies();
                    cookies.set('access_token', response.data.access_token, { path: '/' });
                }
            })
            .catch(function (response) {
            });

Here is my api routes:


//this one is to register using passport
Route::post('/register', 'AuthenticateController@register');

//this one is to login using passport
Route::post('/login', 'AuthenticateController@login');

//this one is to check if user is authenticated
Route::post('/check', 'AuthenticateController@test');

//this one has methods which I want to protect
Route::get('/admin/index', 'AdminController@index');

This is my AuthenticationController which gives me access token, registers and logins, seems to work

    public function register(Request $request){
        $validatedData = $request->validate([
            'name' => 'required|max:55|unique:users',
            'password' => 'required'
        ]);
        $validatedData['password'] = bcrypt($request->password);
        $user = User::create($validatedData);
        $accessToken = $user->createToken('authToken')->accessToken;

        return response()->json(["user" => $user, "token" => $accessToken]);

    }

    public function login(Request $request)
    {
        $loginData = $request->validate([
            'name' => 'required',
            'password' => 'required'
        ]);

        if(!auth()->attempt($loginData, true)) {
            return response(['auth' => 
    false]);
        }
        $accessToken = auth()->user()->createToken('authToken')->accessToken;
        return response(['user' => auth()->user(), 'access_token' => 
    $accessToken, 'auth' => true]);
    }

    public function check(){
        $check= auth()->check();
        return response(['user' => $check]);
    }

Here is my AdminController which trows 401 error when executing index method

//as I understood after login I can protect my api with middleware line for example 10 minutes, but unsuccessfully

 public function __construct()
    {
        $this->middleware('auth:api'); 

    }

    public function index(){
        return response(['foto' => 'testing protection']);
    }

here is my react component axios request which initiated 401 error

axios.get("/api/admin/index", {
        headers : {
            'Content-Type' : 'application/json',
            'Accept' : 'application/json',
            'Authorization' : 'Bearer' + cookie.get('access_token')
        }})
        .then(function (response) {
            alert(response.data.foto);
        })
        .catch(function (response) {
            alert("bad")
        })

//I tried 
// headers.append('Authorization', 'bearer ' + cookie.get('access_token'));
// headers.append('Authentication', 'bearer ' + cookie.get('access_token'));
// headers.append('Authorization', 'JWT ' + cookie.get('access_token'));
// headers.append('Authorization', cookie.get('access_token'));
// but error persists

I just want to protect my api with middleware(auth:api)

also auth->check() gives me false, whic is not good I think


Solution

  • So I found my mistake, instead of using

    headers : {
                'Authorization' : 'Bearer' + cookie.get('access_token')
            }
    
    

    I had to use

    //added space
    headers : {
                'Authorization' : 'Bearer ' + cookie.get('access_token')
            }
    

    but the strange thing I had to do in order this to work is add upcoming lines in Kernel middleware:

    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class
    

    I just tried to use postman instead of axios and got error that something is wrong with sessions and since then it was easy to find needed part