Ruby on Rails HTTP Basic Authentication - ruby-on-rails

I am just starting to learn Ruby on Rails and have a newbie question that I have so far been unable to find the answer for. I have a small app that uses HTTP basic authentication and I have design elements in my view that I only want to display if the request is authenticated. How can I access this information?

You can use the session hash which store data during your session( http://www.tutorialspoint.com/ruby-on-rails/rails-session-cookies.htm) I will recomend using the following tutorial with Http Basic Auth for generating the form: railscasts.com/episodes/21-super-simple-authentication
heres some code you could use
application_controller
helper_method :admin?
def authenticate
authenticate_or_request_with_http_basic do |user_name, password|
session[:user] = "admin" if user_name == 'admin' && password == 'password'
end
end
private
def admin?
session[:user] == "admin"
end

Related

How to setup a remote json API for Rails for authentication and session

I'm new to rails and are have a pretty basic understanding of the Devise Gem. Besides the CRUD and views I'm not clear on what it provides that could help me for a AngularJs app talking to a Rails Json Api.
At the moment I'm hand rolling things ie. for security I have I exchange a HTTP Header token between client (js) and server. I'm also using the Railscast #250 for user authentication - but as I don't see how to apply the SessionController for a remote client.
Are there any strategies I could employ for authentication and managing session via a remote json API?
Thanks!
I personally wouldn't use devise for something like this because there's only a small part of it you'd be using anyways
Dont
You pretty much just don't use a session. All you need to do is pass in basic authentication each time, and in the application controller you determine if its valid, if not just send them back an auth error.
Example request: http://username:password#example.com/api/endpoint
class ApplicationController
before_filter :check_auth!
private
def check_auth!
username, password = ActionController::HttpAuthentication::Basic::user_name_and_password(request)
user = User.find_by(username: username)
if user && user.encrypted_password == SomeEncryptFunction(params[:password])
#current_user = user
else
raise "error"
end
end
end
But if you want to...
Then what you can do is update a DateTime field on the user when they first auth (which starts their session), then on subsequent calls they can just pass a token you give them that you you check for each time they sign in. You also check that only a certain amount of time has passed since they first authed, otherwise their session is invalid.
class SessionsController < ApplicationController
skip_before_filter :check_auth!
before_filter :login!
private
# Note: I don't remember the actual devise method for validating username + password
def login!
user = User.find_by(username: params[:username])
if user && user.valid_password(params[:password])
current_user = user
current_user.update_attributes(
authenticated_at: DateTime.now,
authentication_token: Devise.friendly_token
)
else
raise "error"
end
end
end
class ApplicationController
before_filter :check_auth!
private
def check_auth!
if valid_token(params[:token])
current_user = User.find_by(authentication_token: params[:token])
else
raise "error"
end
end
# Returns true if token belongs to a user and is recent enough
def valid_token(token)
user = User.find_by(authentication_token: params[:token])
user && user.authenticated_at < DateTime.now - 1.day
end
end

devise http basic auth for html format

I have the following configuration:
devise :database_authenticatable
config.http_authenticatable = true
on request:
http://user:password#localhost:3000/
Devise ignores the http auth login and redirects to login page
any thoughts?
Regards
What http_authenticatable give you is the ability to use your HTTP Basic Authentication credentials to log into its own authentication system. You still need to code the http_auth block by yourself, like this:
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == "foo" && password == "bar"
end
warden.custom_failure! if performed?
end
This code should go into your application controller. Make sure you are using warden.custom_failure!, otherwise the devise will enter an infinite loop of redirects.
This worked for me
before_filter :check_auth
def check_auth
authenticate_or_request_with_http_basic do |username,password|
resource = User.find(username)
if resource.valid_password?(password)
sign_in :user, resource
end
end
warden.custom_failure! if performed?
end

How to perform a security authentication check in a Rails server

I would like to use a web server based on Rails.
But I have no idea about how to check a user's identification.
For example, a user named Guest could only perform actions like GET and UPDATE on certain tables, while another user named Admin could perform all possible actions such as POST.
I am new to this area, but I heard there are some technicals like SQL injection could threaten the security of the web server.
So, could you tell me how to check the authentication and how to encrypt password entered by the user?
What you seem to be wanting is authentication and authorization.
For authentication:
https://github.com/plataformatec/devise
https://github.com/vpereira/authlogic
https://github.com/thoughtbot/clearance
For authorization:
https://github.com/be9/acl9
https://github.com/ryanb/cancan
This is strictly speaking out of my personal experience. I have tried all of the suggested authentication and authorization gems mentioned above, but I always came to the conclusion that its not more or less work to just write it yourself, especially when your requirements a very simple. Consider this:
class ApplicationController < ActionController::Base
before_filter :authentication
def authentication
redirect_to '/authentication_form' unless session[:logged_in]
end
def authentication_form
... render the form
end
def login
if params[:username] == 'adam' && params[:password] == 'eva'
session[:logged_in] = true
redirect_to '/restricted_area'
else
render :action => 'authentication_form'
end
end
end
class RestrictedController < ApplicationController
def index
... this action is now restricted
end
end
This is not complete, of course but it demonstrates how easy authentication can be with rails. Instead of checking users and passwords through controller code, you could query the database like this:
if User.find_by_name_and_password(params[:username], params[:password])
session[:logged_in] = true
...
For authorization you would have to save the users identity within the session hash which allows you to restrict access from within every action (provided the controller is a derived from ApplicationController)
I hope, this helps.

Ruby on Rails: how do I make an http password protected sub domain?

I want a subdomain like... admin.example.com
but I want it to require a user and password. Like... the kind that uses teh browser's interface, rather than a database backed authentication system.
what are some good methods of doing this?
It's fairly simple:
# products_controller.rb
before_filter :authenticate
protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == "foo" && password == "bar"
end
end
See: http://railscasts.com/episodes/82-http-basic-authentication
Write a small rack application. Both checking if its the correct subdomain and enforcing basic auth can be done easily.

Rails authenticate_or_request_with_http_basic

When a user tries to connect via this method and it fails. How do I redirect_to? Thanks in Advance.
class ApplicationController < ActionController::Base
protect_from_forgery
USER_NAME, PASSWORD = "admin", "admin"
helper_method :authenticate
private
def authenticate
begin
authenticate_or_request_with_http_basic do |user_name, password|
user_name == USER_NAME && password == PASSWORD
end
rescue
"HTTP Basic: Access denied"
else
redirect_to root_path
end
end
end
Rails - authenticate_or_request_with_http_basic custom "access denied" message
In the past, we've made authenticate a before_filter which will just perform the authenticate_or_request_with_http_basic, and then have our redirects/renders happen in their respective actions.
I just re-read your question & code sample. What exactly are you looking to have happen? A redirect on fail of the authentication?
Edit: I've never done this, but it seems like trying to follow the docs might be your best bet, in particular, the "more advanced basic example."
I ultimately don't know enough about the inner workings of basic auth, but it strikes me as it could also boil down to an Apache/(insert your awesome web server here) configuration. Someone will definitely correct me on that if I'm wrong.

Resources