HTTP令牌:访问被拒绝

时间:2016-03-18 13:23:32

标签: ruby-on-rails mongoid access-token

我收到消息" **HTTP Token: Access denied**"通过浏览器http://localhost:3000/api/v1/tasks.json?auth_token=szVkqLnUbdzbekV8B-n_访问时 但是当我从终端访问“成功curl http://localhost:3000/api/v1/moments.json -H 'Authorization: Token token="szVkqLnUbdzbekV8B-n_"'

”时

这里是代码

  class Api::V1::TaskController < ApplicationController
          before_action :autentifikasi
    def index
        @tasks = current_user.tasks
    end
        private
          def autentifikasi
            authenticate_or_request_with_http_token('Premium') do |token, options|
               @current_user = User.find_by(authentication_token: token)

            end
          end 
        end
     end 
是的,请帮助我!我的代码出了什么问题?

2 个答案:

答案 0 :(得分:3)

您的代码没有任何问题 - 错误在您的测试方法中。

cURL示例正确发送<form class="testimonials__list" action="#" method="get"> <input class="testimonials__radiobutton" type="radio" name="testimonials__radiobutton" id="testimonials__radiobutton_1" value="1"> <label for="testimonials__radiobutton_1"></label> <input class="testimonials__radiobutton" type="radio" name="testimonials__radiobutton" id="testimonials__radiobutton_2" value="2" checked=""> <label for="testimonials__radiobutton_2"></label> <input class="testimonials__radiobutton" type="radio" name="testimonials__radiobutton" id="testimonials__radiobutton_3" value="3"> <label for="testimonials__radiobutton_3"></label> <input class="testimonials__radiobutton" type="radio" name="testimonials__radiobutton" id="testimonials__radiobutton_4" value="4"> <label for="testimonials__radiobutton_4"></label> </form> 标头并同时发送令牌。

在浏览器中请求Authorization: Token只需设置http://localhost:3000/api/v1/tasks.json?auth_token=szVkqLnUbdzbekV8B-n_,因为它是查询参数。这当然会导致身份验证失败。

Rails和大多数理智的框架都不会将HTTP标头和查询参数视为等效。那会让你的应用看起来像瑞士奶酪。

如果您想通过浏览器测试基于令牌的身份验证,您应该使用Postman这样的插件,它允许您设置请求标头。更好的是编写一个实际的自动化集成测试。

答案 1 :(得分:1)

这是因为authenticate_or_request_with_http_token期望Authorization: Token中有request header

您在cURL命令中设置标题,而在浏览器中将其作为查询参数传递。

因此请求标头中没有令牌,因此您的方法在通过浏览器访问时无法找到令牌。

相关问题