Kuf
Kuf

Reputation: 17828

Rails 403 response on session expired when using protect_from_forgery

After a user session has expired, when making a POST or PUT request to any controller that has protect_from_forgery, the server responds with 403, instead of the expected 401 for logged out users.

When a controller returns a 401 code, the client will redirect the user back o the login screen.

I do not want to redirect on each 403, I don't users to get kicked out unless their session expired.

I've tried googling and played around with the different flags as described in the doc without any luck. How can I make protect_from_forgery return 401 when the session expired?

Upvotes: 2

Views: 429

Answers (1)

Kuf
Kuf

Reputation: 17828

I couldn't find a proper solution for this, so I used the following hack:

On the client side, whenever the server returns a 403 error, I immediately make a GET request to an API endpoint that returns 200 if the session exists (user signed in) and 401 otherwise.

I already had the client side logic of redirecting the user to the sign-in page on any 401 errors.

If anyone has a better solution that doesn't require making the seconds call I'll be happy to hear about it.

Upvotes: 0

Related Questions