【发布时间】:2013-05-06 12:42:21
【问题描述】:
我正在使用 Grape 框架为我的 rails 应用程序创建 API。我正在尝试不同的身份验证可能性。有人可以举一个使用 OAuth 进行身份验证的简单示例吗?
【问题讨论】:
-
我来晚了,但看门人可能是相关的:github.com/doorkeeper-gem/doorkeeper
标签: ruby-on-rails authentication oauth grape
我正在使用 Grape 框架为我的 rails 应用程序创建 API。我正在尝试不同的身份验证可能性。有人可以举一个使用 OAuth 进行身份验证的简单示例吗?
【问题讨论】:
标签: ruby-on-rails authentication oauth grape
【讨论】:
您可以在GrapeOAuth2 gem 中找到更多实际示例。您只需要创建 3 个模型来代表您的客户端、令牌和资源所有者、挂载默认端点并保护您的 API。
因此为使用的 ORM 创建 3 个模型并将默认 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 以获得更详细的示例(简单且可自定义)。
【讨论】: