gpt4 book ai didi

ruby-on-rails - 使用Devise的API身份验证(Ruby on Rails)

转载 作者:行者123 更新时间:2023-12-04 04:06:24 26 4
gpt4 key购买 nike

我正在尝试使用devise配置:token_authenticatable在我的项目中通过json添加身份验证。

我有从本文中获取的正在工作的sessions_controller#create代码-http://blog.codebykat.com/2012/07/23/remote-api-authentication-with-rails-3-using-activeresource-and-devise/

def create
build_resource
resource = User.find_for_database_authentication(:email => params[:email])
return invalid_login_attempt unless resource

if resource.valid_password?(params[:password])
resource.ensure_authentication_token! #make sure the user has a token generated
render :json => { :authentication_token => resource.authentication_token, :user_id => resource.id }, :status => :created
return
end
end

def invalid_login_attempt
warden.custom_failure!
render :json => { :errors => ["Invalid email or password."] }, :success => false, :status => :unauthorized
end

问题是 native 设备sessions_controller#create看起来像这样
  def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => after_sign_in_path_for(resource)
end

而且我不知道如何结合这两种创建方法以使身份验证在网站上也可以通过json工作?

更新

工作代码
def create
respond_to do |format|

format.json do
build_resource
resource = User.find_for_database_authentication(:email => params[:email])
return invalid_login_attempt unless resource

if resource.valid_password?(params[:password])
resource.ensure_authentication_token! #make sure the user has a token generated
render json: { authentication_token: resource.authentication_token, user_id: resource.id }, status: :created
return
end
end

format.html do
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => after_sign_in_path_for(resource)
end

end
end

最佳答案

您希望SessionsController#create方法看起来像这样:

class Users::SessionsController < Devise::SessionsController
def create
resource = warden.authenticate!(scope: resource_name, recall: "#{controller_path}#new")
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)

respond_to do |format|
format.html do
respond_with resource, location: redirect_location(resource_name, resource)
end
format.json do
render json: { response: 'ok', auth_token: current_user.authentication_token }.to_json, status: :ok
end
end
end
end

...并确保您已将设备配置为使用客户端将传递的 token 身份验证 key 。

关于ruby-on-rails - 使用Devise的API身份验证(Ruby on Rails),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14322062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com