Adonis jwt authentication with refresh token


#1

I’m trying to setup authentication with JWT token and refresh token, for rest api app. Now, I got it working to issue access_token and refresh_token, but I have troubles making refresh_token work.

When access_token is expired, I send the refresh token back, and I don’t get new access_token.

So my question is: should it be handled automatically (accepting refresh token and issuing new access token), and if not, where do I need to write logic for that ?

Naturally I assumed middleware and tried something like this:


'use strict';

class AuthRefresh {
  async handle({ request, auth }, next) {
    // call next to advance the request
    console.log(request.input());
    // const refreshToken = request.input('refresh_token');
    const refreshToken = request.header('refresh_token');

    const newAccessToken = await auth.generateForRefreshToken(refreshToken);
    console.log(newAccessToken);
    await next(newAccessToken);
  }
}

module.exports = AuthRefresh;

but its not working.

Help is appreciated.


#2

@Perp

Please have a look at this.
https://adonisjs.com/docs/4.0/authentication#_withrefreshtoken


#3

I solved it with this code:

    const { refresh_token, email, password } = request.all();
    if (refresh_token) {
      return await auth
        // .newRefreshToken()
        .generateForRefreshToken(refresh_token);
    }

    return await auth.withRefreshToken().attempt(email, password);
  }