首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用`authenticate_or_request_with_http_token`方法

如何使用`authenticate_or_request_with_http_token`方法
EN

Stack Overflow用户
提问于 2016-01-24 11:59:10
回答 2查看 6.4K关注 0票数 9

我在Rails API中添加了一些身份验证,类似于我的application_controller.rb中的应用程序:

代码语言:javascript
运行
复制
def is_admin
  authenticate_or_request_with_http_token do |token, options|
    if User.find_by(:auth_token => token)
      value = true
    else 
      value = false
    end
  end
end

在我的控制器里:

代码语言:javascript
运行
复制
admin = is_admin
if admin
  @voices = Voice.all.map do |voice| 
    voice.format
  end
else
  @voices = 'Something else'
end

当我登录时,一切正常运行,但是当我没有登录时,我得到了以下错误:Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

虽然没有登录,但我希望得到‘其他东西’的回应,然后我会继续并相应地处理它。

知道为什么会发生这种事吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-24 22:40:10

authenticate_or_request_with_http_token用于在操作之前运行的before_action过滤器中。或者有明确的回报。

如果您只想检查用户是否存在,则使用不发送响应的authenticate_with_http_token

代码语言:javascript
运行
复制
# app/helpers/authorization_helper.rb
module AuthorizationHelper
  # returns true/false
  # sets @current_user if the request is authenticated 
  def authenticate!
    return true if @current_user  # avoid re-querying the DB
    authenticate_with_http_token do |token, options|
      @current_user = User.find_by(:auth_token => token)
    end
  end

  def is_admin?
    authenticate!
  end
end

# app/controllers/api_controller.rb
# or whatever controller you use as a base
class ApplicationController < ActionController::API
  include AuthorizationHelper
end

# in your controller
def index
  if is_admin?
    @voices = Voice.all.map do |voice| 
    voice.format
  else
    @voices = 'Something else'
  end
end
票数 13
EN

Stack Overflow用户

发布于 2019-04-03 07:56:34

此外,您还可以这样做,或者更确切地说,是max的答案的一个选项。

代码语言:javascript
运行
复制
# app/controllers/application_controller.rb
class ApplicationController
  def authorization!
    authenticate_with_http_token do |token, options|
      @current_user = User.find_by(:auth_token => token)
    end

    unless @user.present?
      # You could return anything you want if the response if it's unauthorized. in this
      # case I'll just return a json object 
      return render json: {
        status: 300,
        message: "Unauthorized access in the API"
      }, status: 401
    end
  end
end

# in your controller just add a before_action method
before_action :authorization

def index
  @voices = Voice.all.map do |voice| 
  voice.format
end

在这种情况下,您不需要在每个需要身份验证的请求中添加一个if语句。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34975478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档