Luis Deras
Luis Deras

Reputation: 1269

Get token with JWT without attempting user credentials Laravel?

I'm currently working on a Angular (Front End) - Laravel (API) application. I need to know whether I can make a hybrid log in.

Currently I'm using a stored procedure for the log in. But then if the login was succesful I want to send a JWT token to the client side. Is this possible without calling the JWT attempt method? Does JWT has something like a JWT::getToken($mail); method? If I can't do this, are any other work arounds?

$mail = $request['email'];
$password = $request['password'];

$query = new Query("CALL SP_USER_LOG_IN(?,?, @outputMessage)");
$query->addParameter(1, $mail);
$query->addParameter(2, $password);

$outputMessage = DB::executeQuery($query);

if($outputMessage === null)
{
    //It means the login was successful
    $token = JWT::getToken($mail);

    return ["error" => NULL, "token" => $token];
}
else
{
    return ["error" => $outputMessage];
}

NOTE

I just found out about JWT and it looks like a really good solution since I'm working with a light angular application on the front end. But since I must use a stored procedure, I don't how to proceed.

Upvotes: 0

Views: 1811

Answers (2)

hanmari
hanmari

Reputation: 1474

Update for Laravel 11

  • change to updated composer jwt-auth library package from Php Open Source Saver

    composer require php-open-source-saver/jwt-auth
    
  • follow the installation instructions and alter your User model so it implements the JWTSubject contract and implements methods named getJWTIdentifier and getJWTCustomClaims

  • follow the installation instructions and use its artisan commands to copy the library's default jwt.php file to your config directory and then generate a JWT security key in your .env file

  • create an auth guard entry in the config/auth.php file (here named jwt_auth_guard for clarity)

    'guards' => [
       'jwt_auth_guard' => [
          'driver' => 'jwt',
          'provider' => 'users',
       ],
    ],
    
  • put this method in your controller to get a jwt for a given email address (note: you will need to secure this endpoint)

    public function getJwtFromEmail()
    {
       $validated = request()->validate([
          'email' => 'required|string',
       ]);
       // fetch the user with the matching identifier
       $user = User::where(['email' => $validated['email']])->get()->first();
       if (empty($user)) {
          return response()->json('Could not identify user', 401);
       }
       // the `login` method of the jwt driver for `jwt_auth_guard` will return a jwt
       $token = auth('jwt_auth_guard')->login($user);
       if ($token === false) {
          return response()->json('credentials not accepted', 401);
       }
       $jwt_payload = [
          'access_token' => $token,
          'token_type' => 'bearer',
          'expires_in' => auth('jwt_auth_guard')->factory()->getTTL() * 60,
       ];
       return response()->json($jwt_payload);
    }
    
  • put this method in your controller to get a jwt for a set of credentials (note: you will need to secure this endpoint)

    public function getJwtFromCredentials()
    {
       $validated = request()->validate([
          'username' => 'required|string',
          'password' => 'required|string',
       ]);
       // isolate the request to its credentials
       $credentials = request()->only('username', 'password');
       // the `attempt` method of the jwt driver for `jwt_auth_guard` will return a jwt
       $token = auth('jwt_auth_guard')->attempt($credentials);
       if ($token === false) {
          return response()->json('credentials not accepted', 401);
       }
       $jwt_payload = [
          'access_token' => $token,
          'token_type' => 'bearer',
          'expires_in' => auth('jwt_auth_guard')->factory()->getTTL() * 60,
       ];
       return response()->json($jwt_payload);
    }
    

Upvotes: 0

jfadich
jfadich

Reputation: 6348

Once you've verified the user, grab them from the database then create the token fromUser($user).

if($outputMessage === null)
{
    //It means the login was successful
    $user = User::where('email', $mail)->first();
    $token = JWT::fromUser($user);

    return ["error" => NULL, "token" => $token];
}

Upvotes: 4

Related Questions