2013-05-12 114 views
2

我正在使用Grape框架爲我的rails應用程序創建API。我正在嘗試不同的認證可能性。有人可以舉一個簡單的使用OAuth進行身份驗證的例子嗎?這裏葡萄API和OAuth

回答

0

更實際的例子,你可以在GrapeOAuth2 gem找到。您所需要的只是創建3個模型,代表您的客戶,令牌和資源所有者,安裝默認端點並保護您的API。

因此,創建3種型號的使用ORM和安裝默認的OAuth2令牌端點到您的API:

module Twitter 
    class API < Grape::API 
    version 'v1', using: :path 
    format :json 
    prefix :api 

    helpers GrapeOAuth2::Helpers::AccessTokenHelpers 

    # What to do if somebody will request an API with access_token 
    # Authenticate token and raise an error in case of authentication error 
    use Rack::OAuth2::Server::Resource::Bearer, 'OAuth API' do |request| 
     AccessToken.authenticate(request.access_token) || request.invalid_token! 
    end 

    # Mount default Grape OAuth2 Token endpoint 
    mount GrapeOAuth2::Endpoints::Token 

    # ... 
    end 
end 

可用路線:

POST /oauth/token 
POST /oauth/revoke 

然後保護所需的端點與access_token_required!方法:

module Twitter 
    module Resources 
    class Status < Grape::API 
     before do 
     access_token_required! 
     end 

     resources :status do 
     get do 
      { current_user: current_resource_owner.username } 
     end 
     end 
    end 
    end 
end 

查看README查看更詳細的示例(s實現一個和可定製的)。