[英]is rails “secret_token” still important with config.session_store(:cache_store)?
[英]Rails : Devise with config.session_store :disabled
我正在构建一个Rails 3和gem devise
无状态的RESTful API。
由于我不想存储任何会话,因此通过在config/initializers/session_store.rb
进行定义来禁用它们:
MyApp::Application.config.session_store :disabled
我所有的Warden Strategies(http基本身份验证,令牌身份验证)都不存储任何信息(已stored?
返回false)。
我在控制器中使用了助手authenticate_user!
作为before_filter。 身份验证期间出现以下错误:
NoMethodError (undefined method `[]' for nil:NilClass) :
warden (1.2.1) lib/warden/session_serializer.rb:32:in `fetch'
warden (1.2.1) lib/warden/proxy.rb:212:in `user'
warden (1.2.1) lib/warden/proxy.rb:318:in `_perform_authentication'
warden (1.2.1) lib/warden/proxy.rb:127:in `authenticate!'
devise (2.2.3) lib/devise/controllers/helpers.rb:48:in `authenticate_user!'
第32行的session_serializer中的代码是以下方法:
def fetch(scope)
key = session[key_for(scope)] # it crashes here
return nil unless key
method_name = "#{scope}_deserialize"
user = respond_to?(method_name) ? send(method_name, key) : deserialize(key)
delete(scope) unless user
user
end
由于session
(即@env ['rack.sessions'])等于nil(session_store确实被禁用)而导致崩溃。 这是默认调用,尚未调用策略。
由于我不想猴子打补丁,因此我正在寻找一种禁用session_store的好方法。
谢谢
如果您愿意接受新的设计,建议您使用令牌进行身份验证。 可以通过在每个请求标头中传递令牌来快速设置令牌身份验证并验证请求。
授权:令牌令牌=“ xxx”
如果您有兴趣,我会添加默认的Rails api令牌身份验证代码。
class ApplicationController < ActionController::Base
protect_from_forgery
private
def restrict_access
authenticate_with_http_token do |token, options|
User.exists?(authentication_token: token)
end
end
private
def api_user
authenticate_with_http_token do |token, options|
User.find_by_authentication_token(token)
end
end
end
class UsersController < ApplicationController
before_filter :restrict_access, :except => ['create']
def create
user=User.create(:email=>params[:email],
:password=>params[:password],
:password_confirmation=>params[:password_confirmation])
end
end
class TokensController < ApplicationController
respond_to :json
def create
user = User.authenticate(params[:email],params[:password])
if user
render :json => User.find_by_email(params[:email])
else
render :json => "#{params[:email]} not authorized.", :status => 401
end
end
class User < ActiveRecord::Base
attr_accessible :email, :authentication_token
attr_accessor :password, :password_confirmation
def self.authenticate(email, password)
user= find_by_email(email)
user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) ? user : nil
end
private
def generate_authentication_token
begin
self.authentication_token = SecureRandom.hex
end while self.class.exists?(authentication_token: authentication_token)
self.last_sign_in_at=DateTime.now
self.sign_in_count=self.sign_in_count+1
end
private
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password,password_salt)
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.