For generating Json Web Token we can use this library
First we have to create one dart file where we will store all JWT Constant
abstract class JWTConstants {
static const String accesssTokenSecretKey =
'QBBS0P1H2NLLOTVRWIHR6WXI55G2ZYHH';
static const String refreshTokenSecretKey =
'KF4DMA5VAYCGM60T7N0A46BLOEHXSNX7';
}
We Have to create one class which is responsible for generate Jsons Web Tokens.
import 'package:auth_pro/core/constant/jwt_constant.dart';
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
abstract class JWTUtils {
static String generateAccessToken({required String userId}) {
final jwt = JWT({
'userId': userId,
});
return jwt.sign(
SecretKey(JWTConstants.accesssTokenSecretKey),
expiresIn: const Duration(days: 30),
);
}
static bool verifyAccessToken({required String accessToken}) {
try {
JWT.verify(accessToken, SecretKey(JWTConstants.accesssTokenSecretKey));
return true;
} catch (_) {
return false;
}
}
static String getUserIdFromToken({required String accessToken}) {
final jwt = JWT.decode(accessToken);
// ignore: avoid_dynamic_calls
return jwt.payload['userId'] as String;
}
}
We can use this methods
// For generate Token
final accessToken = JWTUtils.generateAccessToken(userId: user.userId);
// For Validate Tokens
JWTUtils.verifyAccessToken(accessToken: accessToken)