簡體   English   中英

通過API設計定制身份驗證

[英]custom authentication with devise for an API

所以我在這里有一些棘手的組合

Company has many Users
User belongs to Company

通過設計管理用戶進行身份驗證

class User < ActiveRecord::Base

  belongs_to :company

  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

您可以作為用戶登錄並創建全部屬於該公司而不屬於該用戶的對象,例如: Text company.texts

現在,我使用acts_as_api gem創建了一個簡單的API。 為此,我只需要修改我的文本控制器,例如show動作。

class TextsController < ApplicationController

  load_and_authorize_resource

  def show
    #@text = Text.find(params[:id])
    respond_to do |format|
      format.html
      format.json { render_for_api :texts_all, :json => @text }
    end

這在網站上效果很好。 問題是API。 通過用戶模型訪問api時,我不想進行身份驗證。 該公司確實有一個名為:hash的屬性,我想在API中使用它來進行Auth。

我不知道如何使用設計(或任何其他方法)來實現這一目標。 因此,默認情況下, load_and_authorize_resource希望由於我的控制器中的load_and_authorize_resource用戶登錄,這對於html響應而言不錯,但對於json響應而言則不錯。

有任何想法嗎?

感謝您閱讀本文。 如果有不清楚的地方請發表評論!

根據接受的格式標題有條件地應用身份驗證過濾器:

# override in controllers related ot API
def authenticate_user!
  respond_to do |format|
    format.html { super } # just like before
    format.json { enforce_api_auth }
  end
end

現在,API調用將執行自己的身份驗證。

只需使用令牌Authenticateable並隨API上的每個請求發送令牌即可。

這是一個教程。

暫無
暫無

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

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