verify method
Returns a Middleware that verifies the Authorization: Bearer <token> header.
On success, the JWT payload is stored in ctx.request.attributes['auth'].
Implementation
Middleware verify() {
return (ctx, next) async {
final authHeader = ctx.request.headers.value('Authorization');
if (authHeader == null || !authHeader.startsWith('Bearer ')) {
return Response.json(<String, String>{'message': 'Unauthorized'}, status: 401);
}
final token = authHeader.substring(7);
try {
final jwt = JWT.verify(token, SecretKey(secret));
// Store auth data in request.attributes, NOT in body
ctx.request.attributes['auth'] = jwt.payload;
return next();
} on JWTExpiredException {
return Response.json(<String, String>{'message': 'Token has expired'}, status: 401);
} catch (e) {
return Response.json(<String, String>{'message': 'Invalid Token'}, status: 401);
}
};
}