createToken method

Map<String, dynamic> createToken([
  1. String guard = '',
  2. Duration? expiresIn,
  3. bool withRefreshToken = false
])

Create new token for the given user.

The token created is a JWT token that contains the user's ID, the guard's name, and the user's payload. The token is then signed with the secret key from the environment variable JWT_SECRET_KEY.

If withRefreshToken is true, a refresh token is also created and returned in the refresh_token key of the map.

The expiresIn parameter is the duration after which the token will expire. If not provided, the token will expire after 1 hour.

Returns a map containing the following keys:

  • access_token: the JWT token
  • refresh_token: the refresh token if withRefreshToken is true
  • expires_in: the duration after which the token will expire in seconds

Implementation

Map<String, dynamic> createToken([
  String guard = '',
  Duration? expiresIn,
  bool withRefreshToken = false,
]) {
  String secretKey = env('JWT_SECRET_KEY') ?? env<String>('APP_KEY');
  Map<String, dynamic> userId = {'id': _userPayload?['id']};
  if (_userPayload?['id'] == null) {
    userId = {'_id': _userPayload?['_id']};
  }

  final jwt = JWT(
    {
      'user': jsonEncode(_userPayload),
      'type': 'access_token',
      ...userId,
    },
    audience: env('JWT_AUDIENCE') == null
        ? null
        : Audience.one(env<String>('JWT_AUDIENCE')),
    jwtId: env<String?>('JWT_ID'),
    issuer: env<String?>('JWT_ISSUER'),
    subject: env<String?>('JWT_SUBJECT'),
  );
  Map<String, dynamic> payload = {};
  Duration expirationTime = expiresIn ?? const Duration(hours: 1);

  String accessToken =
      jwt.sign(SecretKey('$secretKey$guard'), expiresIn: expirationTime);

  payload['access_token'] = accessToken;

  if (withRefreshToken) {
    final jwtRefresh = JWT({
      ...userId,
      'type': 'refresh_token',
    });
    String refreshToken = jwtRefresh.sign(SecretKey('$secretKey$guard'),
        expiresIn: const Duration(days: 120));
    payload['refresh_token'] = refreshToken;
  }

  payload['expires_in'] =
      DateTime.now().add(expirationTime).toIso8601String();

  return payload;
}