Rails: Basic Authentication with Authlogic

不羁岁月 提交于 2019-11-28 01:40:33

问题


I'm using Authlogic and I would like to implement Basic HTTP Authentication in my controller so I could define which action requires authentication.

I know how to do Basic HTTP Authentication authenticate_or_request_with_http_basic an before_filter, but I would like to here from other how to implement it with Authlogic plugin.

class ItemsController < ApplicationController  
  before_filter :authenticate , :only => [:index, :create]
  ...
end

回答1:


Here is a great screencast that explains, step-by-step, how to use authlogic in your rails project.

Once authlogic is set up, define the following useful authentication-related helper methods in your Application Controller.

def current_user_session
  return @current_user_session if defined?(@current_user_session)
  @current_user_session = UserSession.find
end

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

def require_user
  unless current_user
    store_location
    flash[:notice] = "You must be logged in to access this page"
    redirect_to new_user_session_url
    return false
  end
end

def require_no_user
  if current_user
    store_location
    flash[:notice] = "You must be logged out to access this page"
    redirect_to root_url
    return false
  end
end

Once those methods are defined, you can specify actions that require the user to be logged in:

before_filter :require_user, :only => [:new, :edit]



回答2:


I've had success with the following:

Define a filter method in application_controller.rb

def require_http_auth_user
  authenticate_or_request_with_http_basic do |username, password|
    if user = User.find_by_login(username) 
      user.valid_password?(password)
    else
      false
    end
  end
end

Then in your controller you can do the following:

  before_filter : require_http_auth_user

You can then use:

http://username:password@yoursite.com (i.e. http basic authentication)

Hope this helps.



来源:https://stackoverflow.com/questions/2285474/rails-basic-authentication-with-authlogic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!