Jwt-auth: Remember Me and Forgot Password functionality in JWT Auth

Created on 28 Sep 2015  路  21Comments  路  Source: tymondesigns/jwt-auth

Hi,

I have used JWT Auth for logging in my users to the application. But there is no information about how to give facility to users to remember them on the site and how to reset password when password is forgotten. There are ways to do this with laravel inbuilt authentication, but cant figure out how to do the same with JWT Auth. Does JWT Auth use Auth\Guard.php or is there anything else I need to change.

Thanks in advance! :)

Most helpful comment

@shraddhabanerjee
Hey !
So , the thing is JWT Auth doesn't come with any thing to handle Remember Me or Forgot Password functionanlity , it's something that you will have to handle

1) About Remember Me

What you can do is use the JWTAuth and set time to expire to a really long time if the user selects Remember Me .. that way the token will not expire and you can reuse the token anytime , you don't have to ask the user to log in again.

2)About Forgot Password

JWTAuth has got nothing to do with forgot password , you will have write code by yourself to handle if the user cannot remember the password .
Using the standard approach of emailing a randomly generated reset password link should do the trick !

_peace_

All 21 comments

JWT is not responsible for this; it provides "stateless authentication" for a User but the actual authentication is still handled by Laravel under water.

@mirague Thanks for the reply.
So you mean I need to use Laravel authentication if I need remember users functionality on my site?
Or I can use JWT Auth for login and use the laravel inbuilt authentication for remember me functionality.

I have:
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'Please check the username and password'], 401);

And as per laravel, I need Auth::attempth and pass remember flag.
if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
// The user is being remembered...
}

SO how this is possible using JWT Auth?

The client needs to store the token locally, in for example a cookie or local storage.

This is the API-endpoint I use in one of my projects. With the client I post to api/auth with the user's email and password, if successful it will return a JSON response with "token": "ey..", this is what you store locally and on every request after you send the token with the Authorization: Bearer <token here> header.

   /**
     * Authenticates a user and sends them a Token to be used on future requests.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function authenticate(Request $request)
    {
        $credentials = $request->only('email', 'password');

        try
        {
            // verify the credentials and create a token for the user
            if ( ! $token = JWTAuth::attempt($credentials))
            {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e)
        {
            // something went wrong
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        // if no errors are encountered we can return a JWT
        return response()->json(compact('token'));
    }

Thanks a lot for the reply @mirague.

My authenticate function is just same like yours.

But I need something like this,

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

    try {
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'Please check the username and password'], 401);
        }
    } catch (JWTException $e) {
        return response()->json(['error' => 'Please check the username and password'], 500);
    }

    // if no errors are encountered we can return a JWT
    return response()->json(compact('token'));
}

Hi, this library is awesome.
I am searching for the _Remember Me_ approach.
I have seen in JWTAuth class that the method _attemp_ has a second param, _$customClaims_

attempt(array $credentials = [], array $customClaims = [])

It can be used to make the call as said in the docs? http://laravel.com/docs/5.0/authentication#authenticating-users

if (Auth::attempt(['email' => $email, 'password' => $password], $remember))
{
    // The user is being remembered...
}

did anyone fix this functionality?

@juniorov & @jasmad
Nope. I didn't fix the functionality yet.

Your API doesn't store the session (at least it shouldn't), that is where the "remember" information would be stored. JWTAuth validates username and password only and then generates a token to send back.

If you want your client application to remember the user, you have to store the token in a permanent cookie or local storage for your client application to look for and then skip the login page if found.

I would also add in some method to validate the token before letting them into the site before they get an error that the token is invalid.

@shraddhabanerjee
Hey !
So , the thing is JWT Auth doesn't come with any thing to handle Remember Me or Forgot Password functionanlity , it's something that you will have to handle

1) About Remember Me

What you can do is use the JWTAuth and set time to expire to a really long time if the user selects Remember Me .. that way the token will not expire and you can reuse the token anytime , you don't have to ask the user to log in again.

2)About Forgot Password

JWTAuth has got nothing to do with forgot password , you will have write code by yourself to handle if the user cannot remember the password .
Using the standard approach of emailing a randomly generated reset password link should do the trick !

_peace_

@harshitdkanodia
Thanks for the reply, I have done the forgot password functionality using the Laravel inbuilt functionality, just overridden the methods.

Still stuck with remember me functionality. Either you can use JWT Auth or Laravel Auth. So Laravel Auth attempt function provides $remember flag for remember me functionality, but in JWT Auth its not possible. Will try to use the solution you have mentioned and get back.
Thanks.

@harshitdkanodia, thanks for the reply, I understand your reasoning with the first bullet point, and will be sure to follow your advice.

@harshitdkanodia I couldn't find a way to increase expiry time for particular user. Can you guide me on that?

@evivz if you read the documentation, you can set your custom claims.

$customClaims = ['exp' => date('Y-m-d', strtotime('+2 week'))];

$token = JWTAuth::attempt($credentials, $customClaims)

This is accurate for 0.5.x, but in 1.0.x, the attempt method no longer has the custom claims argument.

There are couple ways to do this (the common solution is to call JWTAuth::customClaims($array) before attempt), but if the expiration differences are truly user-based, I would recommend taking advantage of the JWTSubject interface itself, which requires User instances to identify any custom claims:

// inside your User class:
public function getJWTCustomClaims() {
    if ($this->can('use-extended-token-timelines')) {
        $expiration = Carbon::now('UTC')->addWeeks(2)->getTimestamp();
        return ['exp' => $expiration];
    }
    return [];
}

(This is an example I took from an actual project to give more context. The can function comes from the Laravel Authorizable trait; the implementation of the use-extended-token-timelines ability is irrelevant for the example)

Hey!
About the forgot password fonctionality can we implement it in cakephp not Laravel?
and if yes how to do it since
thanks

This library exclusively supports Laravel at the moment. I suspect it would be a very great challenge to get it to work in CakePHP...

(Also AFAIK, Cake doesn't have a built-in password reset)

Hi @shraddhabanerjee, could you please share your code for the forgot password functionality, I am implementing the same thing in laravel and angularjs using JWTAuth.
Thanks.

I used this tutorial to use JWT in cake :
http://www.bravo-kernel.com/2015/04/how-to-build-a-cakephp-3-rest-api-in-minutes/
it works fine and it's very good one but I didn't figure out how to implement reset password

@majdichaabene Ouch :+1: @shraddhabanerjee to the rescue

@shraddhabanerjee I am also implementing the forgot password functionality usingJWT Auth with Laravel api and angular js UI. Could you please share the code.
Thanks in advance :-)

There is a great tuto for the FOrgot Password with Lumen 6

https://medium.com/@nbulian/lumen-6-laravels-reset-passwords-b5157d2d4717

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Rasoul-Karimi picture Rasoul-Karimi  路  3Comments

loic-lopez picture loic-lopez  路  3Comments

marciomansur picture marciomansur  路  3Comments

lloy0076 picture lloy0076  路  3Comments

heroghost picture heroghost  路  3Comments