我正在为我的rails应用程序创建API。我正在尝试不同的身份验证可能性。谁能给出一个使用OAuth进行身份验证的简单示例?
发布于 2013-07-11 02:52:20
嗨,这里,你有一个例子吗?
发布于 2016-11-07 18:24:06
你可以在GrapeOAuth2 gem中找到更多实际的例子。您需要做的就是创建3个模型来代表您的客户端、令牌和资源所有者,挂载默认端点并保护您的API。
因此,为使用的ORM创建3个模型,并将默认的OAuth2令牌端点挂载到您的应用编程接口:
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看看自述文件中更详细的例子(简单的和可定制的)。
https://stackoverflow.com/questions/16505830
复制相似问题