Given the following Rails 4.2 controller:
class Api::UsersController < ApplicationController
def index
respond_to do |format|
format.html do
flash[:error] = 'Access denied'
redirect_to root_url
end
format.json do
render json: {}, status: :unauthorised
end
end
end
end
When, with RSpec 3, I try to call this index
action and expect to have the status 401 I always have the status 200.
The only moment where I got the 401 is to replace the index
action content with head 401
but I would like to respond with the error 401 and also build a "nice" body like { error: 401, message: 'Unauthorised' }
.
Why is the status: :unauthorised
ignored ?
@houssembouallagui Get the token from server and store in localStorage. Don't include authorization header for this route. On the server side, allow this route to go through without jwt authorization because at this moment you don't have the token. For all the other routes, follow the answer and the blog.
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field containing at least one challenge applicable to the target resource.
Use error code instead of it's name:
render json: {}, status: 401
I had to replace my controller with this following:
class Api::UsersController < ApplicationController
def index
respond_to do |format|
format.html do
flash[:error] = 'Access denied'
redirect_to root_url
end
format.json do
self.status = :unauthorized
self.response_body = { error: 'Access denied' }.to_json
end
end
end
end
Using render
is not preventing the called action to be executed. Using head :unauthorized
is returning the right status code but with a blank body.
With self.status
and self.response_body
it's working perfectly.
You can see have a look to the source code my gem where I had this issue here: https://github.com/YourCursus/fortress
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With