Context: a Rails app in production, hosted on Heroku, that has around 800 users.
Ruby 2.4.2
Rails 5.1.4
Devise 4.3.0
For some reason, I have seen a few users experience an error:
ActionController::InvalidAuthenticityToken
[GEM_ROOT]/gems/actionpack-5.1.4/lib/action_controller/metal/request_forgery_protection.rb:195
For requests to POST /students/:id/registrations.
It is intermittent, and very few users experience the error.
Clients are Safari 11.0 on iPads.
ApplicationController:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!, unless: :devise_controller?
before_action :restrict_from_students, unless: :devise_controller?
# ...
end
RegistrationsController:
class RegistrationsController < ApplicationController
skip_before_action :restrict_from_students, only: :create
# ...
end
Is there some scenario (re-POSTing the request, auth timeout but submitting, lack of JS) that would cause this? I cannot seem to reproduce it.
I was having a similar issue.
Use rescue_from in the application controller and redirect somewhere useful with a notification. In my case I attempt to redirect the user back to where they were to reattempt their action, or to the home page as a fallback.
Example for rails 5:
class ApplicationController < ActionController::Base
rescue_from ActionController::InvalidAuthenticityToken,
with: :handle_invalid_token
def handle_invalid_token
redirect_back fallback_location: root_path,
notice: 'Stale session detected'
end
end
Thanks to the rubber duck, I have reproduced the issue.
Sign out
Go "back" to the cached app UI.
Click the button to generate a POST request.
Observe the exception.
The solution here is to use rescue_from to likely redirect the user to the sign in page.
Thank you rubber duckie!
Related
When i try to use the sign_up method of Devise, i get an internal server error but, after create the user.
My application.rb:
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session, only: Proc.new { |c| c.request.format.json? }
before_action :configure_permitted_parameters, if: :devise_controller?
respond_to :json
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [ :username ])
end
end
Here the output,
Any ideas? 🤔
I am supplementing this with Doorkeeper, but please do not alter the operation of Devise. I also did not use Warden on my own anywhere on the app.
This issue seems to be the problem you are having:
https://github.com/heartcombo/devise/issues/4603
They suggest clearing the cookies of your browser
this usually happens when you are upgrading a bunch of stuck including
devise in one branch And than you get back to some other branch for
something and you have this newer cookie in your browser. Simple
solution is to clear cookies in browser.
Other answers mention upgrading devise version
I recently added a piece of code to my ApplicationController to set the timezone of the current block to the one specified by the user.
class ApplicationController < ActionController::Base
around_action :set_time_zone, if: :current_user
protect_from_forgery with: :exception
private
def set_time_zone(&block)
Time.use_zone(current_user.time_zone, &block)
end
end
For some reason when I try to sign in i get a
ActionController::InvalidAuthenticityToken in Devise::SessionsController#create
If i remove
around_action :set_time_zone, if: :current_user
I can sign in and if i add it back after I sign in, everything works as expected.
Any ideas?
This page has good info on the problem, but I was weirdly able to fix this in Rails 5 by putting protect_from_forgery above the around_action/filter. Hope it helps!
Cheers!
I use Devise gem for authenticating users and locally (development env) I always get this ActionController::InvalidAuthenticityToken exception on devise::session/create action, no big deal I thought and added some dirt:
class ApplicationController < ActionController::Base
include EmailConcern
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :authenticate_user!
def handle_unverified_request
true
end
...
end
All right, no more authenticity_token exceptions, I don't mind if it happens only in dev env. But! There is another problem - :authenticate_user! is never worked, so current_user is always nil and I always getting redirected with 401 unauthorized to new session path again. User's credentials are valid and user exists in the DB.
router.rb
Rails.application.routes.draw do
resources :coupons
devise_for :users, path: 'u'
What could be the origin of this issue?
ruby-2.2.2#rails-4.2.0
Sign-in works fine on Chrome, but doesn't work on Safari (or I assume other Webkit browsers). I get this error message after you sign in ("The change you wanted was rejected. Maybe you tried to change something you didn't have access to."):
According to my heroku logs, this is what's happening:
2016-12-07T14:14:23.778153+00:00 app[web.1]: Can't verify CSRF token authenticity
2016-12-07T14:14:23.778899+00:00 app[web.1]: Completed 422 Unprocessable Entity in 2ms (ActiveRecord: 0.0ms)
2016-12-07T14:14:23.785544+00:00 app[web.1]:
2016-12-07T14:14:23.785547+00:00 app[web.1]: ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
I believe i'm sending the proper CSRF token, but something seems to be malfunctioning. This is my current application_controller.rb:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
after_action :flash_to_headers
# this is so that json requests don't redirect without a user
before_action :authenticate_user!
# before_action :authenticate_user!, unless: request.format == :json
# before_action :user_needed, if: request.format == :json
before_action :set_paper_trail_whodunnit
before_action :set_global_search_variable
def set_global_search_variable
#q = Person.ransack(params[:q])
end
def user_needed
unless current_user
render json: { 'error' => 'authentication error' }, status: 401
end
end
def flash_to_headers
return unless request.xhr?
response.headers['X-Message'] = flash_message if flash_message
response.headers['X-Message-Type'] = flash_type.to_s if flash_type
flash.discard # don't want the flash to appear when you reload page
end
private
def flash_message
[:error, :warning, :notice].each do |type|
return flash[type] unless flash[type].blank?
end
nil
end
def flash_type
[:error, :warning, :notice].each do |type|
return type unless flash[type].blank?
end
nil
end
(Changing protect_from_forgery with: to null_session just causes an endless loop of returning to the login screen.)
This question references a similar problem, but doesn't discuss the complication of Devise. Supposedly Devise handles this issue already, but it somehow isn't working here. Many of these answers are years old, so i'm not sure how relevant they would be today.
I've also tried searching for bugs in the actual Devise Github repo, but I don't seem to be getting anywhere with the suggestions in those threads. Lots of suggestions to edit the application controller, but many times that seems to crash the entire app.
This app runs Ruby 2.2.5 and Rails 4.2.7.1. Would updating to Rails 5 help solve this issue?
It also has an existing (and probably hacky) override for making admin accounts; the person signs up through Devise and then is given admin access through another field called approved manually in the pqsl shell. I'm not sure if that could be related.
The app is on Github, for anyone who wants to take a look:
https://github.com/yamilethmedina/kimball
As it turns out, my problem was solved by this answer. It wasn't in the application controller after all, but in config/initializers/session_store.rb.
This was my initial session_store:
Logan::Application.config.session_store :cookie_store, key: '_cutgroup_session', secure: (Rails.env.production? || Rails.env.staging?)
Upon doing further research, I found this suggestion:
Rails.application.config.session_store :cookie_store, key: "_rails_session_#{Rails.env}", domain: all
This still didn't work; however, it would give a 401 error in the logs (instead of 422) and redirect back to the login page as opposed to showing the error screen I screenshotted above.
Finally, I removed the domain: all part from the end of Rails.application.config.session_store :cookie_store, key: "_rails_session_#{Rails.env}" worked for me on Safari (cookies weren't blocked at any point from the browser). Now, i'm able to log in when the project is deployed on Heroku.
The bounty was a heavy price to pay, but at least the commenters helped me clarify my thinking and find a solution! If someone else comes across this question and comes up with a better one, i'll upvote it instead, but I think i've got it now.
try :
controller/application.rb
protect_from_forgery with: :null_session
and
override you Device controller
sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
skip_before_filter :verify_authenticity_token, :only => [:destroy]
end
I'm getting a redirect loop. I have a clear idea why, user is logged out, redirected to login page (welcome#index) and user is still logged out and we have an endless loop.
How do I get out of loop?
I read about several options.
before_action :require_login placing it inside controllers where login is required. EASY, but a lot of copy paste, we love dry don't' we?
except, before_action :require_login, :except => root? I couldn't find details about except. I'm getting a lot of hits on before_filter which seems to be deprecated.
skip_before_action same here, I can only find bits and pieces :(
There should be a better way to handle these, is it rails way to do check routes level in config/routes.rb?
Application controller:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :current_user
before_action :require_login
private
def current_user
#current_user ||= Dedit::User.find(session[:user_id]) if session[:user_id]
end
private
def require_login
redirect_to root_path unless current_user.present?
end
end
login page controller:
class WelcomeController < ApplicationController
layout 'basic'
def index
if current_user.present? then redirect_to dedit_path end
end
end
before_action :require_login, except: [:index]