0
votes

I'm wondering how to implement tymon jwt 1.0.0 rc2 with Cartalyst Sentinel 2.0 authentication package in Laravel 5.6 to take advantage of throttling and others Sentinel features.

Inside AuthController I have this login() method as mentioned in jwt-auth Docs enter link description here to validate the credentials and generate a token.

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

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

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

What I did is the following

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

    if (! Sentinel::authenticate($credentials))
        return response()->json(['error' => 'Unauthorized'], 401);

    $token = auth()->attempt($credentials);
    return $this->respondWithToken($token);
}

But i don't think this is the right way because there is a double authentication, first by Sentinel and the second by jwt. and this is bad for performance.

And second workaround is to modify attempt() method inside JWTGuard class that resides in vendor/tymon/jwt-auth/src folder.

the default is the following

public function attempt(array $credentials = [], $login = true)
{
    $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);

    if ($this->hasValidCredentials($user, $credentials)) {
        return $login ? $this->login($user) : true;
    }

    return false;

}

and I changed it like this

public function attempt(array $credentials = [], $login = true)
{
    if ($user = Sentinel::authenticate($credentials)) {
        return $this->login($user);
    }

    return false;
}

I don't now if this is a right solution or not ?

2

2 Answers

0
votes

in jwt config change with this

'auth' => Tymon\JWTAuth\Providers\Auth\Sentinel::class,

And in auth controller you can used this function

use Tymon\JWTAuth\Facades\JWTAuth;

/**
 * Handle a login request to the application.
 *
 * @param loginRequest $request
 *
 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
 */
public function login(loginRequest $request) {

    $credentials = array(
        'email'    => $request->email,
        'password' => $request->password,
    );

    if (! $token = JWTAuth::attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    } else {
        return $this->respondWithToken($token);
    }
}

/**
 * Get the token array structure.
 *
 * @param  string $token
 *
 * @return \Illuminate\Http\JsonResponse
 */
protected function respondWithToken($token)
{
    return response()->json([
        'access_token' => $token,
        'token_type' => 'bearer',
        'expires_in' => auth('api')->factory()->getTTL() * 60
    ]);
}

And now you can logged in.

0
votes

Just use auth('api')->user() to get user using jwt or passport with sentinel