Find_for_database_authentication vs Find_by in Rails Devise app? - ruby-on-rails

So, I'm trying to set up a React frontend and Rails backend with devise, and the Rails side is supposed to be an internal API. It's the first time I've ever done this, so I'm struggling with authentication. Specifically, in my SessionsController, I have this code:
def create
resource = User.find_for_database_authentication(email: params[:email])
return invalid_login_attempt unless resource
if resource.valid_password?(params[:password])
sign_in :user, resource
return render nothing: true
end
invalid_login_attempt
end
This always returns 401 Unauthorized. I check the result of calling valid_password? and it is always false.
However, if I replace find_for_database_authentication with find_by, the valid_password? works with no problems. Why is this? It's okay if for now the user can only enter his email and not his password, but this really confuses me. It also bugs me that this doesn't use any token checking (different issue).
On the side, I'm also wondering about whether or not CSRF tokens are okay for internal APIs (should I use a different token-auth?), and how I'm supposed to include a CSRF token with a login form if the user isn't logged in yet, but I guess those are questions for another post. Thanks for any help.

Related

How to fix Brakeman redirect issue with multiple rest endpoints

I'm currently working on a solution for doing redirects in RoR because I got an error within the brakeman report saying that I have to fix redirects in a proper way.
I understand what the message says and how to solve it within one controller action.
But now I got the following. During the instantiation of the new method I set the HTTP_REFERER header which can be used in the create action.
This is giving me a Brakeman warning which can be found on the following link
Suppose I got the following controller with multiple endpoints:
def new
#my_model_set = MyModel.new
#referer = request.env['HTTP_REFERER'] # We want to redirect to this referer after a create
end
def create
...
if #my_model_set.save
flash_message :success, t('notification.item_created', type: #my_model_set.model_name.human)
if params[:referer].present?
redirect_to params[:referer]
else
redirect_to admin_my_model_set_path
end
else
...
end
end
I already tried to fix this by using the redirect_back method from RoR but that's using the referer link of the create method which I don't want to use.
if #my_model_set.save
flash_message :success, t('notification.item_created', type: #my_model_set.model_name.human)
redirect_back(fallback_location: admin_my_model_set_path)
else
...
end
The main problem in your code is that params[:referer] can be set by your user (or an attacker forging a link for your user) to an arbitrary value by appending ?referer=https://malicious.site to the url. You will then redirect to that, which is an open redirect vulnerability.
You could also argue that the referer header is technically user input, and you will be redirecting to it, but I would say in most cases and modern browsers that would probably be an acceptable risk, because an attacker does not really have a way to exploit it (but it might depend on the exact circumstances).
One solution that immediately comes to mind for similar cases would be the session - but on the one hand this is a rest api if I understand correctly, so there is no session, and on the other hand, it would still not be secure against an attacker linking to your #new endpoint from a malicious domain.
I think you should validate the domain before you redirect to it. If there is a common pattern (like for example if all of these are subdomains of yourdomain.com), validate for that. Or you could have your users register their domains first before you redirect to it (see how OAuth2 works for example, you have to register your app domain first before the user can get redirected there with a token).
If your user might just come from anywhere to #new and you want to send them back wherever they came from - that I think is not a good requirement, you should probably not do that, or you should carefully assess the risk and consciously accept it if you want to for some reason. In most cases there is a more secure solution.

Is it possible to do Devise sign in, out, etc without any redirection whatsover?

I'm using Devise, but not using the Devise controllers directly because I'm performing all of the actions through a custom built GraphQL API. One issue I have, for example, is that after enabling confirmable, if a user tries to sign in and I call Devise::Controllers::Helpers#sign_in the user gets redirected to /api/v1/users/sign_in, which doesn't exist and it would be wrong even if it exist. Instead, I need the failure to sign in to be returned back to my code (return value, exception, whatever), so that my API can encode that response to the frontend.
How can I do that?
For example, this is my log in function:
def resolve(email:, password:)
user = User.find_for_authentication(email: email)
if user&.valid_password?(password)
context[:sign_in].call(user)
{ current_user: user }
else
{ errors: [{ message: 'Email or password incorrect.' }] }
end
end
context[:sign_in] is set up in the GraphqlController by including Devise::Controllers::Helpers and then simply:
context = {
current_user: current_user,
sign_in: method(:sign_in),
sign_out: method(:sign_out)
}
Note: I am not using GraphqlDevise because I don't want to use Devise Token Auth, I'm using cookies.
I believe passing devise's sign_in/sign_out methods via context is probably a deadend.
The suggestion in the comment to your question from #Int'l Man Of Coding Mystery is good ie you could use: https://github.com/graphql-devise/graphql_devise.
If you're not keen in introducing another dependency and figuring out how to wire everything you can perhaps go with overriding devise's SessionController.
See for some examples here: Rails - How to override devise SessionsController to perform specific tasks when user signs in?
(but also don't hesitate to look at the source code for the matching Devise release: https://github.com/heartcombo/devise/blob/master/app/controllers/devise/sessions_controller.rb)
Depending on your use case you might be even able to do what you need by using some of the config options - e.g. you can perhaps try to override after_sign_in_path etc.

Restful Authentication -- how to log in a user without password

I've got a cross-website integration to handle. Basically I'm passing a param into the rails application and if it evaluates correctly ... then I'd like to log a user in.
Can this be done without the users password?
something like simply evaluating the password as true?
This is called "token authentication" and is supported by Devise, or can be relatively easily ginned up on your own. You want to generate a non-guessable secret token (your param), and then use that in lieu of a username. The devise wiki has links to a couple of examples:
https://github.com/plataformatec/devise/wiki/How-To:-Simple-Token-Authentication-Example
If you want a lighter-weight solution, you can also simply generate an auth token (using something like bcrypt) and then do something like:
#user = User.find_by_auth_token(params[:auth_token])
if #user is nil, then return a 403.

How do I get AuthLogic to skip Password validation?

I think I'm just missing something obvious. I send a user a perishable token embedded in a link. They click on it, and they come back to the site. I want to log them in automatically --- authenticated by their perishable token, not the password. (I'm not building a banking app).
This seems like this should be simple, but all the examples I've found require a password. How do I skip this completely? When I try to get UserSession.create to work, it reports a validation error and will not create the user session. What is the way around this?
#user = User.find_by_perishable_token(params[:token])
if #user
if !current_user
# skip sign-in
UserSession.create!(#user.email)
# => error "You did not provide any details for authentication."
...
I have googled extensively but haven't found the answer.
Doesn't UserSession.create take a user object as it's first argument? If so, couldn't you just do:
UserSession.create(User.find_by_perishable_token(params[:token]))
#current_user_session = UserSession.find
Or is that where you're running into problems?

Rails: Accessing the username/password used for HTTP Basic Auth?

I'm building a basic API where user information can be retrieved after that user's login and password are correctly sent.
Right now I'm using something like this:
http://foo:bar#example.com/api/user.xml
So, what I need to do is access the user/password sent in the request (the foo and bar) but am not sure how to access that info in a Rails controller.
Then I'd check those variables via a quick User.find and then set those as the username and password variables for authenticate_or_request_with_http_basic.
It's possible I'm looking at this at the completely wrong way, but that's where I'm at right now. :)
The answer to your question of how to get the credentials from the request is this:
user, pass = ActionController::HttpAuthentication::Basic::user_name_and_password(request)
However authenticate_or_request_with_http_basic is all you need to do basic auth:
class BlahController < ApplicationController
before_filter :authenticate
protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
# you probably want to guard against a wrong username, and encrypt the
# password but this is the idea.
User.find_by_name(username).password == password
end
end
end
authenticate_or_request_with_http_basic will return a 401 status if credentials are not supplied, which will pop up the username/password dialog in a browser. If details are given then those are passed to the block provided. If the block returns true the request goes through. Otherwise the request processing is aborted and a 403 status is returned to the client.
You can also check out Railscast 82 (thats were the code above is from):
http://railscasts.com/episodes/82-http-basic-authentication
The rails plugin Authlogic supports this functionality (as well as much more) out of the box. You could root around in the source for it, or simply integrate it into your existing application.
Edit:
After digging around the source code for Authlogic, I found this file which uses the following piece of code to grab the username and password:
def authenticate_with_http_basic(&block)
#auth = Rack::Auth::Basic::Request.new(controller.request.env)
if #auth.provided? and #auth.basic?
block.call(*#auth.credentials)
else
false
end
end
I'd look a bit further into where it all goes, but I've got to get to bed. Hope I was of some help.

Resources