verify method
Verifies a given JWT token and returns the payload if it is valid.
The expectedType
parameter is the expected type of the token. If the
token is not of this type, an Unauthenticated
exception will be thrown.
The guard
parameter is the guard to use when verifying the token. The
secret key will be concatenated with the guard before verifying the
token.
Returns a map containing the payload of the token if it is valid.
Throws an Unauthenticated
exception if the token is invalid or expired.
Implementation
Map<String, dynamic> verify(String token, String guard, String expectedType) {
String secretKey = env('JWT_SECRET_KEY') ?? env<String>('APP_KEY');
try {
final jwt = JWT.verify(
token,
SecretKey('$secretKey$guard'),
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'),
);
if (jwt.payload['type'] != expectedType) {
throw Unauthenticated(message: 'Invalid token');
}
return jwt.payload;
} on JWTExpiredException {
rethrow;
} on JWTException {
throw Unauthenticated(message: 'Invalid token');
}
}