简体   繁体   English

使用无会话设计时current_user是什么?

[英]what is current_user when using session-less devise?

I have disabled sessions in my rails api with for example config.skip_session_storage = [:http_auth, :token_auth] 我已在Rails api中禁用了会话,例如config.skip_session_storage = [:http_auth, :token_auth]

Does it make sense to "logout" of the api? “注销” api是否有意义? If it does how can I get current_user because the code below throws current_user =nil error or the warden.authenticate fails. 如果可以,我如何获取current_user,因为下面的代码引发current_user = nil错误或warden.authenticate失败。

# class Api::V1::SessionsController < Devise::SessionsController

  def create
   # create token
  end

  def destroy
    # We don't need this because the user is authenticated by the token.
    warden.authenticate!(:scope => resource_name, :store => false, :recall => "#{controller_path}#failure")
    current_user.reset_authentication_token!
    render :status => 200,
           :json => { :success => true,
                      :info => t("devise.sessions.signed_out"),
                      :data => {} }
  end

An API has no state because it's not relying on the browser to cache anything. API没有状态,因为它不依赖浏览器来缓存任何内容。 Typically if you want to secure an API, you give each user some kind of access token (via the rendered html or in the javascript directly (see the gon gem)) and then operate the API over SSL, requiring each call to have that access token. 通常,如果您想保护API,则需要为每个用户提供某种访问令牌(通过呈现的html或直接在javascript中(请参见gon gem)),然后通过SSL操作API,要求每个调用都具有该访问权限令牌。

For example, you could call https://mysite.com/api/v1/users?token=... 例如,您可以致电https://mysite.com/api/v1/users?token=...

And then get the current_user based on that token. 然后基于该令牌获取current_user

Alternatively, you can include the token in your header whenever you do an API call. 另外,您可以在每次进行API调用时在标头中包含令牌。 Either way, you will want to secure it with SSL so that nobody routing the request (eg a fake Starbuck's wifi) can sniff the request, grab the token, and use it themselves. 无论哪种方式,您都希望使用SSL保护它,以便路由请求的人(例如假的星巴克wifi)无法嗅探请求,获取令牌并自己使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM