verify method

Middleware verify()

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 (Context ctx, Next next) async {
    final authHeader = ctx.request.headers.value('Authorization');
    if (authHeader == null || !authHeader.startsWith('Bearer ')) {
      return Response.json({'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 await next();
    } on JWTExpiredException {
      return Response.json({'message': 'Token has expired'}, status: 401);
    } catch (e) {
      return Response.json({'message': 'Invalid Token'}, status: 401);
    }
  };
}