tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.28k stars 1.55k forks source link

Why attempt() method doesn't throw any Exception? #1674

Open nikolaof opened 5 years ago

nikolaof commented 5 years ago

Subject of the issue

While using the auth()->setTTL(1)->attempt($credentials) I realized that if it doesn't match the credentials with a user in DB, it doesn't return an exception like UnauthorizedHttpException. For that reason one has to enclose the above command inside an if clause.

In contrast methods like check() did return one and exception is handled by the global handler.

Your environment

Q A
Bug? dunno
New Feature? no
Framework Laravel
Framework version 5.7
Package version 1.0.0
PHP version 7.x.y

Steps to reproduce

public function authenticate(Request $request)
{
        $credentials = $request->only('email', 'password');
        $token = auth()->setTTL(1)->attempt($credentials);
        return response()->json(compact('token'));
}

The above code will return a JSON object with token:false which is setted in the local storage or wherever and will not throw an exception

To make it work one could do this or to throw a custom UnauthorizedHttpException

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

        if (! $token = auth()->setTTL(1)->attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 400);
        }
        return response()->json(compact('token'));
 }

From the other hand, methods like check() if fail, return an exception and there is no need to wrap it inside an if clause

    public function checkIfValid()
    {

         $isvalid = auth()->parseToken()->check()) 
         return response()->json(compact('isvalid'));
    }

Is this behaviour of attempt() expexted or not? Is there any reason that doesn't throw exceptions?

shirshak55 commented 5 years ago

auth attempt returns try or false only isn't it? Using methods like JWTAuth::parseToken(); etc will return exception bro.