Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SPA using Laravel 5.8 / Vue - auth() returns token true instead of token value

I'm creating a SPA using Laravel 5.8 and VUE and I'm using JWT to Authenticate by a token.

The authentications work but it returns true as the value instead of the token value. I think to have corrupted my config and I'm not able to fix it again.

My login method is:

    $credentials = request(['email', 'password']);

    if (Auth::attempt($credentials)) {
        if (! $token = auth()->attempt($credentials, false)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

         return $token;
     }

The result is "true" but I need the JWT value.

Some few steps back:

I'm using: tymon/jwt-auth

the Auth:

function auth($guard = null)
{
    if (is_null($guard)) {
        return app(AuthFactory::class);
    }

    return app(AuthFactory::class)->guard($guard);
}

the config/auth.php

  'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],

    'users' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

Any suggetsion to check my config?

like image 614
Uncoke Avatar asked Dec 07 '25 14:12

Uncoke


2 Answers

You should use the JWTAuth facade provided by the package:

        if (! $token = \JWTAuth::attempt($credentials)) {
            return Response::json(['error' => 'Unauthorized'], 401);
        }
like image 173
Thiago Barcala Avatar answered Dec 09 '25 05:12

Thiago Barcala


you can use guard('api') or guard('users') method, since you have multiple guards

    $credentials = request(['email', 'password']);

    if (!$token = auth()->guard('api')->attempt($credentials)) {
         return response()->json(['error' => 'Unauthorized'], 401);
    }
    
    return $token;
like image 32
Ivan Fretes Avatar answered Dec 09 '25 05:12

Ivan Fretes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!