如何使用授权令牌对我的rails api进行ajax调用

时间:2014-03-01 05:34:55

标签: ruby-on-rails jsonp

我可以使用curl发出以下请求并收到200 OK,我无法通过ajax请求获得200 OK。我在下面试过这个没有运气

无法使其正常工作

$.ajax({
    beforeSend: function (xhr) { xhr.setRequestHeader ('Authorization', 'Token 6ff1fed470ec2ddaf8b3af958461990G') },
    type: "GET",
    url: "http://testurl.abc.com/api/v1/category/",
    dataType: "json"
}).done(function( msg ) {
    console.log( msg );
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log( "Request failed: " + textStatus );
    console.log( errorThrown );
});

好请求

curl http://testurl.abc.com/api/v1/category -I -H 'Authorization: Token token='6ff1fed470ec2ddaf8b3af958461990G''

HTTP/1.1 200 OK 
Cache-Control: max-age=0, private, must-revalidate
Content-length: 0
Content-Type: application/json; charset=utf-8
Date: Sat, 01 Mar 2014 05:05:45 GMT
Etag: "c676e7d052ef40b8ff298c158f8bd7af"
Server: WEBrick/1.3.1 (Ruby/2.0.0/2014-02-24)
Set-Cookie: request_method=HEAD; path=/   
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 7ba9b354-e3d0-4408-81df-8d5e991875e7
X-Runtime: 0.006036
X-Ua-Compatible: chrome=1
X-Xss-Protection: 1; mode=block
Connection: keep-alive

任何线索都表示赞赏。

喝彩!

更新:它看起来不像授权:令牌令牌= {token}未正确设置。如果我在charles代理中编辑失败的请求以包含它,那么它按预期工作。现在只是弄清楚为什么我的setRequestHeader调用被忽略了。

module Api                                                                                                                                                                                                  
       module V1                                                                                                                                                                                           
         class CategoryController < ApplicationController                                                                                                                                                                                                                                                                              
        before_filter :restrict_access                                                                                                                                                                  
        def index                                                                                                                                                                                       
            @categories = Category.all                                                                                                                                                                  

            render :json => @categories, :callback => params[:callback]                                                                                                                                                                                                                                                                                                                                                                                                                                    
        end                                                                                                                                                                                             

        def restrict_access                                                                                                                                                                                                                                                                                                                                                                                         
                authenticate_or_request_with_http_token do |token, options|                                                                                                                             
                  ApiKey.exists?(access_token: token)                                                                                                                                                   
                end                                                                                                                                                                                                                                                                                                                                       
        end                                                                                                                                                                                                                                                                                                                                                                                                        
      end                                                                                                                                                                                                                                                                                                                                                                                                        
    end                                                                                                                                                                                                 
end                                                                                                                                                                                                         



class ApplicationController < ActionController::Base                                                                                                                                                        

  protect_from_forgery with: :exception                                                                                                                                                                     
  before_filter :cors_preflight_check                                                                                                                                                                       
  after_filter :cors_set_access_control_headers                                                                                                                                                             


    def cors_set_access_control_headers                                                                                                                                                                       
     headers['Access-Control-Allow-Origin'] = '*'                                                                                                                                                         
     headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'                                                                                                                          
     headers['Access-Control-Request-Method'] = '*'                                                                                                                                                       
     headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'                                                                                            
    end                                                                                                                                                                                                       

    def cors_preflight_check                                                                                                                                                                                  
       if request.method == "OPTIONS"                                                                                                                                                                         
         headers['Access-Control-Allow-Origin'] = '*'                                                                                                                                                        
         headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'                                                                                                                         
         headers['Access-Control-Request-Method'] = '*'                                                                                                                                                      
         headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'                                                                                           
         render :text => '', :content_type => 'text/plain'                                                                                                                                                   
       end                                                                                                                                                                                                    
     end                                                                                                                                                                                                      
  end                                                                                                                                                                                                         

1 个答案:

答案 0 :(得分:1)

这是我们使用的一些工作代码:

(function(token) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","******",true);
    xmlhttp.setRequestHeader("Authorization", "Token " + token);
    xmlhttp.send();
})(tracker);

我认为您的问题将是beforeSend来电,但似乎是recommended way to create an authentication token $.ajax


Rack-CORS

您的应用中的CORS政策可能存在问题

如果您没有在生产中收到请求,但是在本地,则可能是CORS问题。通过使用Rack-CORS gem,您将能够允许不同的请求类型到您指定的端点

以下是我们使用的代码:

config.middleware.use Rack::Cors do
  allow do
    origins '*'
    resource '/data*', :headers => :any, :methods => :post
  end
end