2013-05-12 201 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实现一个和可定制的)。