Rails开发环境:禁用knock JWT认证及允许非XHR请求绕过认证的方法
Hey Mike, great question—dealing with JWT auth during development can definitely slow down testing API endpoints directly in the browser or with simple tools like curl. Let’s break this down into two tailored solutions depending on your needs:
If you don’t need any authentication checks while building and testing locally, the simplest approach is to override Knock’s authentication method in your base controller to skip it in development:
class ApplicationController < ActionController::API include Knock::Authenticable # Override Knock's authenticate_user to skip in development def authenticate_user # Only enforce auth in production/staging return unless Rails.env.production? || Rails.env.staging? super end end
This way, all API endpoints will be accessible without a JWT token when you’re working locally, but will still require proper authentication in production. If you need to keep auth for specific controllers in development, you can override the method directly in those controllers instead.
If you want to keep JWT auth for frontend XHR requests (like calls from React/Vue apps) but skip it for direct browser visits or non-XHR tools (curl, Postman without XHR headers), you can check the request type in your authentication logic:
class ApplicationController < ActionController::API include Knock::Authenticable def authenticate_user # Skip auth only for non-XHR requests in development return if Rails.env.development? && !request.xhr? super end end
How this works:
request.xhr?checks if the request is an XMLHttpRequest (most frontend frameworks send this automatically via theX-Requested-With: XMLHttpRequestheader).- Direct browser visits, basic curl calls, or Postman requests without the XHR header will bypass auth in development, letting you quickly inspect JSON responses.
- Frontend XHR requests will still require a valid JWT token, so you can test your auth flow as normal during development.
Bonus: Testing XHR Requests Locally
If you want to simulate an authenticated XHR request with curl, just add the XHR header along with your JWT:
curl -H "X-Requested-With: XMLHttpRequest" -H "Authorization: Bearer YOUR_JWT_TOKEN" http://localhost:3000/api/your-endpoint
⚠️ Important Note: Make sure you never remove the Rails.env.development? check—you don’t want unauthenticated access to your production API!
内容的提问来源于stack exchange,提问作者Mike

