在设计身份验证后,在客户端中存储数据

时间:2015-12-10 17:21:59

标签: ruby-on-rails devise

在我的rails应用程序中,在使用devise成功登录后,我想调用一个返回令牌的外部服务。如何将其传递给客户端以便它被持久化(例如在localStorage中)?

class Users::SessionsController < Devise::SessionsController
  def create
    super
    login_to_chat #successful login
  end

  def login_to_chat
    uri = URI('https://xxxxxx.ws/authenticate')

    https = Net::HTTP.new(uri.host,uri.port)
    https.use_ssl = true

    req = Net::HTTP::Post.new(uri)
    req['Content-Type'] = 'application/json'
    req.body = params[:user].slice(:username,:password).to_json

    res = https.request(req)

    if res.kind_of? Net::HTTPSuccess
      json = JSON.parse(res.body)

      # how can I pass json['public_token'] to the client?

    end
  end
end

1 个答案:

答案 0 :(得分:0)

我不确定哪种解决方案最适合您的环境。我的想法是:

  1. 将令牌写入控制器中的cookie(用户可以轻松访问)

    cookies[key] = value
    
  2. 这是&#39;创建&#39; Devise中的方法:: SessionsController

    def create
      self.resource = warden.authenticate!(auth_options)
      set_flash_message(:notice, :signed_in) if is_flashing_format?
      sign_in(resource_name, resource)
      yield resource if block_given?
      respond_with resource, location: after_sign_in_path_for(resource)
    end
    

    因此,您可以覆盖&#39; after_sign_in_path_for&#39;将您的令牌作为参数的方法,客户端知道该参数,您可以做任何您想做的事情

  3. 万一,&#39; login_to_chat&#39;需要很长时间,我们可以在后台进行,然后通过websocket

  4. 通知客户端