簡體   English   中英

使用API​​時如何使用Devise進行身份驗證

[英]How to use Devise for authentication when using an API

我知道還有其他與此類似的問題,但是在我的情況下,沒有一個答案有效。 我正在嘗試通過API對用戶進行身份驗證。 更具體地說,我有一個iPhone應用程序充當“客戶端”,它將帖子請求發送到我擁有的會話控制器。 這里是:

class V1::SessionsController < ApplicationController

  def create
    @user = User.find_by_username(params[:username])

    if @user
      if @user.valid_password?(params[:password])
        sign_in(@user)
        render :create
      else 
        render_error_for @user
      end
    else
      render json: {
        status: 'ERROR',
        data: ['Incorrect Username']
      }, status: :unauthorized
    end
  end 
end

我在網上閱讀了sign_in(@user)應該登錄用戶的信息,但這不能正常工作。 另外,我讀到您應該在登錄用戶之前重新加載用戶,例如: @user.reload 這也不起作用。 我想知道這是否與我不是從Devise::SessionsController繼承的事實有關。 我學習了如何在線制作這樣的會話控制器,所以可能是問題所在。

我測試的方法是通過在rails控制台中運行user.last_sign_in_at ,但是我得到的只是nil ,我敢肯定,這意味着user.last_sign_in_at無法成功登錄用戶。 任何幫助表示贊賞,謝謝。

UPDATE

def create
    @user = User.find_by_username(params[:username])

    if @user
      if @user.valid_password?(params[:password])
        @user.last_sign_in_at = Time.now
        render :create
      else 
        render_error_for @user
      end
    else
      render json: {
        status: 'ERROR',
        data: ['Incorrect Username']
      }, status: :unauthorized
    end
  end

我找到了可能的解決方案,但是我沒有將其標記為解決方案,因為在我看來,該解決方案並不安全。 我實質上是用我自己的過程來創建會話,(然后將last_sign_in_at分配給last_sign_in_at字段)來代替Devise的過程。 這樣安全嗎? 還是這樣做不是一個好主意? 硬編碼Devise的sessions#create操作由於某些原因無法正常工作。 我推測這與以下事實有關:這是API,而不僅僅是常規網站。

正如您所說, More specifically, I have an iPhone app acting as the "client" and it sends posts requests to a sessions controller I have

因此我可能認為您需要的響應將包括用戶信息和身份驗證令牌。

嘗試這種方式:

class SessionsController < Devise::SessionsController

  skip_before_action :verify_authenticity_token # skip CSRF check for APIs
  respond_to :json

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

 def respond_with(resource, opts = {})
   render json: resource.as_json(only: [:id,:email, :name, ... ])
                      .merge!({token: resource.token})
 end
end

關於令牌,您可以在:jwt_authenticatable, :jwt_revocation_strategy gem中檢查:jwt_authenticatable, :jwt_revocation_strategy

因此,響應將具有用戶和令牌:用戶將是用戶信息,令牌將是此用戶的身份驗證令牌。 然后,您需要在下次調用另一個后端請求時存儲該令牌,以確保下次將其包含在標頭中作為授權。

在后端,我們根據身份驗證令牌獲取當前用戶。

您可以嘗試基於設備設計用於API身份驗證的device-token-auth gem。

請檢查描述用法的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM