Home > Software design >  use laravel JWT authentication only for api without affecting web
use laravel JWT authentication only for api without affecting web

Time:03-30

I have an issue with authentication in laravel web, I only what to use the JWT authentication for the api only, I notice whenever I change guard in defaults to web 'guard' => 'web' and I try to login with postman using my api it will not work and this error show("message": "Method Illuminate\Auth\SessionGuard::factory does not exist.") but the web will work, if I change it to 'guard' => 'api' I will not be able to login in the web but the api postman login will work.

Only web will work

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
], 

Only api will work

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
], 

Route

Route::group([
    'prefix' => 'auth'
], function () {
    Route::post('login', [AuthController::class, 'login']);
    Route::post('logout', [AuthController::class, 'logout']);
    Route::post('refresh', [AuthController::class, 'refresh']);
    Route::post('me', [AuthController::class, 'me']);
});

Controller

class AuthController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }


    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if ($token = $this->guard()->attempt($credentials)) {
            return $this->respondWithToken($token);
        }

        return response()->json(['error' => 'Unauthorized'], 401);
    }


    public function me()
    {
        return response()->json($this->guard()->user());
    }


    public function logout()
    {
        $this->guard()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }


    public function refresh()
    {
        return $this->respondWithToken($this->guard()->refresh());
    }


    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $this->guard()->factory()->getTTL() * 60
        ]);
    }

    public function guard()
    {
        return Auth::guard();
    }
}

I just want to use JWT authentication for only the api without affecting the web, Thanks

CodePudding user response:

What defaults.guard config does is setting the default guard to be used if none specified.

If you want 2 different authentication methods and guards you should specify each by name in your middlewares.

So instead of Route::middleware('auth')->get(...);
you should write Route::middleware('auth:api')->get(...);

If you want to protect all routes in a group you can do it in app/Http/Kernel.php by adding this lines:

protected $middlewareGroups = [
    'web' => [
        ...
        'auth:web'
    ],
    'api' => [
        ...
        'auth:api'
    ],
];

CodePudding user response:

you can use this

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

and in controller where you need api guard use this

auth('api')

for example in login controller

 public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        if (!$token = auth('api')->attempt($validator->validated())) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $token = auth('api')->claims(['user' =>  auth('api')->user()])->attempt($validator->validated());
        return $this->createNewToken($token);

  
    }
  • Related