custom authentication with devise for an API

2019-09-01 01:49发布

问题:

so i have a little tricky combination here

Company has many Users
User belongs to Company

The User is managed for authentication with devise

class User < ActiveRecord::Base

  belongs_to :company

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

You can login as a User and create Objects that all belong to the Company of that, not to the user, for example: Text. (company.texts)

now i created a simple API using the acts_as_api gem. for this i simply have to modify my text-controller, f.e. the show action.

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

this works quite fine on the website. the problem is the API. i don't want to authenticate when accessing the api via the user model. the company does have a attribute called :hashwhich i want to use for Auth in the API.

i don't have any idea how to achieve this using devise (or any other method). so by default devise wants a user to be logged in because of load_and_authorize_resource in my controller which is fine for the html response but not for the json response.

any ideas?

thanks for reading this. please leave a comment if something is unclear!

回答1:

Just use Token Authenticatable and send the token with each request on your API.

Here is a tutorial for it.



回答2:

Conditionally apply auth filters based on accepted format headers:

# 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

Now API calls enforce their own auth.