Devise getting 401 unauthorized right after sign in - ruby-on-rails

Rails 4.2, Ruby 2.2.0, Devise 3.5.7
I have an Admin model. In ideal case after sign in, it should be redirected to homepage. But in my case, it is signing in successfully, but while redirecting, somehow authentication fails, causing it to redirect to the sign in page again.
The controller which gets called is:
Class Admin::DashboardsController < ApplicationController
before_action :authenticate_admin!
before_filter :authorize
def show
end
end
In first view, I thought it is a problem with authorize method. But code never reaches it.
authenticate_admin! is a devise method. And I don't know if there is a point in debugging.
Surprisingly it works on local, but results in 401 Unauthorized after deploying.
Logs

I think the application is fine. It has to do something with your server configurations. Something might be missing.
As you said it is working locally, there might be something that you changed in your configurations for the server, that might be causing the problem. Check your config files, application.rb or any other subdomain files that you might be using.

Related

problems with sign out, cookies and devise on rails

I have been trying to sign in after signing out on my application using devise but I am having an issue with the cookies I think because I have to refresh my web page in order to sign in again. I tried using activerecord-session_store gem and I follow the steps to configure it. I mean, I installed the gem, I generated the recommended migration on the gem documentation and generated the table using rake db:migrate command, I also changes the session_store.rb file but I feel that I am missing something to make it work since I tried it and the same happens. Please help me if you feel I am missing something or if you have other solution for this problem. Many thanks in advance
You are probably getting a "Can't verify CSRF token authenticity" error. Can you check your server logs?
In your ApplicationController please add the following and check if you get an error.
protect_from_forgery with: :exception

CSRF Detection fix provider_ignores_state: true not saving session after successful Devise Omniauth-Facebook Authentication

My application was working ok, and then I updated to Rails 5.0.1. After this my app no longer authenticated with Facebook and came up with the following error in the logs:
Authentication failure! csrf_detected:
OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected
So, in accordance to what people on StackOverflow suggested, I changed my omniauth config to include the provider_ignores_state: true setting, which suppressed that error.
config.omniauth :facebook, 'xxx', 'xxxxxxxxxxxxx',{
scope: 'public_profile,email,user_birthday,etc...',
info_fields: 'name,first_name,etc...',
provider_ignores_state: true
}
This made everything work just fine; at least in development running locally, but when I pushed the code to my staging server, the app successfully authenticates with Facebook, supposedly "signs" the user in and redirects to root_path() - and then fails authentication and redirects back to users/sign_in.
To help diagnose the problem i put a logging line above the relevant call (to see if it was being executed) such as:
logger.debug " (OmniauthCallbacksController#facebook) about to sign_in_and_redirect with id: #{#user.id} email: #{#user.email} uid: #{#user.provider_uid}"
sign_in_and_redirect #user, event: :authentication
My OmniauthCallbacksController handler for the Facebook provider there for does seem to reach 'sign_in_and_redirect' - but for reasons I cannot determine on my staging environment, it never actually saves the session to a cookie. There are no errors in the logs (in debug mode) to demonstrate there was any kind of exception thrown - except that the query to increment the log_in_count on the user doesn't actually run any query:
(2.4ms) COMMIT
(0.2ms) BEGIN
(0.2ms) COMMIT
Which looks weird (no actual update query, whereas in development i can see the log_in_count etc be incremented). But its the only other indication that something goes wrong. After that, it fails the authenticate_user! check and redirects back to the sign_in_url.
This is sending me mad - Is this a bug, or is there a fix for this issue?
We had the same error come up for omniauth-github. What fixed it for us (aside from the provider_ignores_state: true hack) was the URL in the link to github's authentication site. Originally we'd entered the entire URL for github OAuth (https://github.com/login/oauth/authorize?client_id=#{ENV["GITHUB_CLIENT_ID"]}&scope=repo), but changing it to the omniauth format of just /auth/github fixed this CSRF error (as well as a no route found error when we tried mocking out / testing our OAuth). Leaving this here in case anyone else has a similar issue in the future!
I was finally able to solve this issue, but I still don't understand WHAT went wrong. Basically, created a "empty" Rails 5 project and setup a brand new devise using the omniauth-facebook gem and settings for my main app - deployed to a cloned instance of the staging server and it worked! Most of the code was the same; but when I replaced the devise.rb initializer with the one from the new app, the old code proceeded to work on the stagingg server again. Interestingly, I coped the Omniauth config from the old one to the new app, so it must have been something wrong with another of Devise's modules...and not with Omniauth itself.
In either case, it's working now. So I will put this to bed and leave this here in case another person encounters the same problem; and while I cant say what was specifically wrong, these are the steps I used to debug/fix my particular problem.

Why can't I deauthorize Rack-mini-profiler for non admin users

I am trying to install Rack-mini-profiler on my ROR application.
I installed the gem and the profiler works great in development but I can't deauthorize specific requests for non admin users.
I placed the following code in my ApplicationController before_filter
def authorize_mini_profiler
if current_user.nil?
Rack::MiniProfiler.deauthorize_request
return
elsif is_admin_user
Rack::MiniProfiler.authorize_request
return
end
Rack::MiniProfiler.deauthorize_request
end
In debug I saw that the deauthorize method is called but the profiler is still displayed.
I even tried using this code
def authorize_mini_profiler
Rack::MiniProfiler.deauthorize_request
end
but still, every request by any user displays the profiler.
Does anyone knows what might be the problem?
Well, for those who run into the same problem...
Deeper debugging found that the gem is configured for ignoring the authorization mechanism on init. In order to enable profiling only on some cases (e.g. non production or only for admin users) you need to override the default configuration in application.rb (or preferably some specific config file):
Rack::MiniProfiler.config.authorization_mode = :whitelist if Rails.env.production?
otherwise the configuration is set to :allowall

Devise Omniauth callback error

I have a web application running Devise and Omniauth to authenticate a user on Facebook. When I click on a link to log in though Facebook, it routes me to
/users/auth/facebook/callback?state=[state]code=[code]
Which is correct. But the page gives me the following error.
uninitialized constant ApplicationController::DeviseController
The line that it points to is in the ApplicationController
DeviseController.respond_to :html, :json
I've included my relevant code here https://gist.github.com/testrecord/5050992 In addition, I do have it set up in the initializer.
Has anyone seen an error like this? Any help is appreciated.

NoMethodError when attempting to use open_id_authentication

I'm currently adding OpenID login support for a Rails 3.0.0 application.
I have already installed ruby-openid (the gem) and open_id_authentication (the plugin). However, after following the steps required to set up both (from the READMEs), I am still getting this error:
undefined method `authenticate_with_open_id'
I tried Googling the problem, but most threads seem to date from years ago and remain suspiciously unanswered.
Am I missing something obvious? What is causing this problem? Note that I have had no problems switching to file-based stores in environment.rb, so I am sure that the plugin is correctly installed.
Update: Some unresolved problems of the same nature:
http://railsforum.com/viewtopic.php?id=23151
Experiencing a similar error; oddly, I have this working on Rails 3.2 on another branch, and can't figure out the difference; anyhow I found that I got a little further by following suggestions here: Rails 3.0.9 + open_id_authentication
That is, adding the line include OpenIdAuthentication after class SessionsController < ApplicationController:
class SessionsController < ApplicationController
include OpenIdAuthentication
But now I get a Completed 401 Unauthorized in my log, and see a blank page -- just and tags. Ugh.
Update: Ooh, got further; I followed this post: open_id_authentication - "OpenIdAuthentication.store is nil. Using in-memory store." problem
and as they suggested, "added an initializer named config/initializers/openid.rb with this inside":
require 'open_id_authentication' # this was needed, but not described in the referred-to post
OpenIdAuthentication.store = :file
I was then directed to the OpenId provider and was able to click "allow", but on returning to my app, I now see:
NoMethodError in SessionsController#create
undefined method `encoding' for nil:NilClass
Anyhow, finally, I found a restful routes problem and fixed that, and now logging in works!

Resources