用于API的自定义身份验证 [英] custom authentication with devise for an API

查看:178
本文介绍了用于API的自定义身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一点棘手的组合在这里

 公司有很多用户
用户属于公司

用户通过设计进行身份验证

  class User< ActiveRecord :: Base 

belongs_to:company

devise:database_authenticatable,:可注册,可恢复,可记忆,可跟踪,可验证

您可以以用户身份登录,并创建所有属于该公司的对象,而不是用户,例如:文本。 ( company.texts



现在我创建了一个简单的API,使用 acts_as_api <宝石code
为此我只需要修改我的文本控制器,展示动作。

  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。



我没有任何想法如何使用设计(或任何其他方法)实现这一点。
所以默认情况下,devise希望用户登录,因为我的控制器中的 load_and_authorize_resource ,这对html响应是好的,但不适用于json响应。 p>

任何想法?



感谢您的阅读。如果有什么不清楚,请留下评论!

解决方案

只需使用Token Authenticatable,并发送令牌与API上的每个请求。 / p>

这是一个教程。


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!

解决方案

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

Here is a tutorial for it.

这篇关于用于API的自定义身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆