Rails: Return a 401?

Ruby on-RailsHttp

Ruby on-Rails Problem Overview


I'd like to return a HTTP 401 error as part of my permission_denied method for declarative_authorization.

# triggered when a user accesses a page that they don't have access to
def permission_denied
  # render my default 401 error page?
end

How would I do this? (Pardon the question if it's stupid... I know how to render the 401.html page in my public directory, but I don't think it returns the 401 HTTP header, which is what I'm after.)

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You can add the :status option

def permission_denied
  render :file => "public/401.html", :status => :unauthorized
end

Solution 2 - Ruby on-Rails

Here so you don't have to dig through comments for a modern answer.

The previous answer has been deprecated in Rails 5.1

Throw any of these into your controller action:

Render A File/Template

render :file => "public/401", :status => :unauthorized

Render JSON

render status: :unauthorized, json: { error: "You are not authorized to access this resource. Verify that you are passing passing your token." }

Render Nothing

head :unauthorized

See ActionController#head

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionneezerView Question on Stackoverflow
Solution 1 - Ruby on-RailsGarrettView Answer on Stackoverflow
Solution 2 - Ruby on-RailsCTS_AEView Answer on Stackoverflow