How to skip Devise authentication when using an API key?

前端 未结 4 992
慢半拍i
慢半拍i 2020-12-28 10:04

I\'m using Devise on my application and would like to create a global API key that can access JSON data of anyone\'s account without having to log-in.

For example, s

4条回答
  •  北海茫月
    2020-12-28 10:54

    You can do this with your before_filter in your Controller.

    Currently, you probably have something like:

    class SomeController < ApplicationController
      before_filter :authenticate_user!
    end
    

    Instead of calling this, you can define a different method (ideally in ApplicationController)

    class ApplicationController < ActionController::Base
      before_filter :authenticate_or_token
    
      private
      def authenticate_or_token
        if params[:api_key] == 1234
          @current_user = User.new(:admin => true, :any => "other", :required => "fields")
          return current_user
        end
        authenticate_user!
      end
    

    I would recommend using a more robust method of authentication such as OAuth, but this should work for a simple 1-key based authentication.

提交回复
热议问题