I'm trying to setup Rails_admin with devise in order to force authentication to go into the admin panel but I'm getting unauthorized messages and being redirected to the login page.
I've done this kind of integration between Devise and Rails_Admin before and didn't have any problem but this time I'm getting a lot of troubles with it. Any idea of what might be happening?
Thanks in advance
config.authenticate_with do
warden.authenticate! scope: :user
end
config.current_user_method(&:current_user)
I had the same problem. Changing the session_store key fixed the problem for me.
# config/initializers/session_store.rb
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_changed_key_session'
This comment helped me to find this solution : https://github.com/activeadmin/activeadmin/issues/2957#issuecomment-49748165.
Related
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.
I recently added rails_admin to my app to modify its database without going into the backend.
In config > initializers > rails_admin.db I have:
RailsAdmin.config do |config|
config.authorize_with do
authenticate_or_request_with_http_basic('Site Message') do |username, password|
username == 'foo' && password == 'bar'
end
end
config.main_app_name { ['app_name', 'Admin'] }
config.actions do
dashboard # mandatory
index # mandatory
new
export
bulk_delete
show
edit
delete
show_in_app
end
end
When viewed in localhost:3000/admin, a window appears asking for the name and password I put into the app.
I'm being a little unorthodox not using CanCan, Devise, or the like but I don't think my small site would require that much work for authentication (I'm willing to work with those, though, if there is no other solution to this).
After deploying to Heroku, the /admin page still works, but completely bypasses the authentication step. I don't see why Heroku would be so picky. Is it not taking the authenticate_or_request_with_http_basic method? Or is it that I missed a step in Heroku deployment (I just used git push heroku master)?
Thanks in advance.
I found the answer, answering my own question in case anyone else runs into this issue.
This was actually an issue I was having with Git, not Heroku. The initializers (which contained my authorization code), were not being tracked with git. I simply needed to type "git add config/" into the command line to track the config files (including the initializers), commit changes, then upload to Heroku.
So I have a Rails application using Devise, and I'm a little confused as to how Devise Rememberable works. I have :rememberable enabled in my User model. When I go to log in WITHOUT checking the Remember me? box, I'm still logged even after a browser close AND a computer restart.
If this is a case, what is the point of rememberable? Am I missing something?
Thanks!
Removing expire_after: 504.hours from config/initializers/session_store.rb seemes to have solved the problem, rather than removing the file altogether.
Source: how to clear devise session on browser close?
I'm following Ryan Bate's instructions for using Omniauth to set up third party authentication, except that I'm trying it with Facebook rather than Twitter, which he sets up in RailsCast 235.
After installing omniauth-facebook gem, and setting up the initializer
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, 'APP_ID', 'APP_SECRET'
end
I should be able to go to localhost:3000/auth/facebook and be presented with the Facebook login (even though it won't eventually work because we haven't set up the callback url yet) However, when i go to that url, I get this error
{
"error": {
"message": "Error validating application.",
"type": "OAuthException",
"code": 101
}
}
and the url actually changes to
https://graph.facebook.com/oauth/authorize?response_type=code&client_id=APP_ID&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Ffacebook%2Fcallback&scope=email%2Coffline_access
On my app, I've set up Devise and followed the instructions on the Devise wiki for integrating Facebook authorization https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview
Can anyone tell me what the problem might be?
Doing a Google search on the error message revealed that quite a few people have experienced this problem in recent weeks but couldn't find anyone with a solution
I searched for 101 and I stumbled upon this page. As you can see, that error stands for Invalid API key, so I believe that the problem lies in where you defined your key.
You should set up your key and your secret in a separate file (for clarity and security) but be mindful that Rails loads files in alphabetical order so the file that defines those constants should have a name that comes before the file that configures the oauth connection. In my case, I created a file called constants.rb, which comes before devise.rb. Also, make sure to keep this file away from source control. You don't want other people to have your keys and secrets.
# config/initializers/constants.rb
FACEBOOK_KEY = 'string'
FACEBOOK_SECRET = 'string'
Then configure your connection in your devise file if you are using devise or in your omniauth file if you are using simple omniauth:
# config/initializers/devise.rb|omniauth.rb
require 'omniauth-facebook'
config.omniauth :facebook, FACEBOOK_KEY, FACEBOOK_SECRET
Now, there is a better way to do this using ENV variables. I recommend the Figaro gem as it really simplifies configuring apps.
If you want to display the facebook dialog page as a popup, you'll want to use
config.omniauth :facebook, FACEBOOK_KEY, FACEBOOK_SECRET, :display => 'popup'
And follow this question later down the road.
And, if you are on Windows, you'll need a certificate so that the SSL connection does not fail. The solution to this problem is clarified by Arcolye here.
Finally, to test your login locally, all you need to do is define your Site URL as http://localhost:3000/. That's all there is. You do not have to define your canvas URL.
In the past, I had an issue using localhost with Facebook applications. What I ended up doing was to create an entry in my host file on my computer to point fbdev.com to localhost and just used "fbdev.com" in place of localhost in the app settings on facebook.
I was getting the same error but I had forgotten to restart the server after adding my APP_ID and APP_SECRET :-P
Maybe that will help?
First, ensure you have the following in routes.rb:
# Auth callback routes
match '/auth/:provider/callback' => 'sessions#create' # This route is hit when a user gives the app permissions (the auth hash will be in request.env['omniauth.auth'])
match '/auth/failure' => 'sessions#failure' # This route is hit when a user doesn't give the app permissions
Second, ensure you have the following in config/initializers/omniauth.rb:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, 'APP_ID', 'APP_SECRET', :scope => 'email', :display => 'page'
end
Third, ensure you have http://localhost:3000/ set as your Canvas URL in your Facebook app settings (https://developers.facebook.com/apps/).
You should then be able to simply redirect your users to http://localhost:3000/auth/facebook to display the authentication dialog to them.
it is the first time I am working with devise and I am a confused by the massive amount of files and configuration options.
Before installing devise, I used the nifty:authentication from ryan bates - which I didn't delete before installing devise and I guess now my routes and/or controllers are a little screwed up.
well, after singing in on /users/sign_in devise tries to redirect me to
http://localhost:3000/sessions/user
but I get the error:
No route matches "/sessions/user"
I don't know where is the error, any help appreciated
I put all the relevant code in a gist: https://gist.github.com/972058
thanks in advance
In my case, I had a session controller which was causing issues. Removing resources :sessions from the routes file should solve the problem. That was because I had previously created a session manager. Once gone, I did not see the issue again.
That's because you don't have root path in your routes. As you can read in devise page: https://github.com/plataformatec/devise
After signing in a user, confirming
the account or updating the password,
Devise will look for a scoped root
path to redirect. Example: For a :user
resource, it will use user_root_path
if it exists, otherwise default
root_path will be used. This means
that you need to set the root inside
your routes
To specify redirect page you need to do this https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in
btw. you don't need sessions controller to make it works