문제 설명
포도 API 및 OAuth (Grape API and OAuth)
I'm working on creating API for my rails application using Grape framework. I'm trying different authentication possibilities. Can someone give a simple example of using OAuth for authentication?
참조 솔루션
방법 1:
hi there here do you have an example
https://github.com/opperator/warden‑oauth2
방법 2:
More actual example you can find in GrapeOAuth2 gem. All you need is to create 3 models that will represent your clients, tokens and resource owners, mount default endpoints and protect your API.
So create 3 models for used ORM and mount default OAuth2 tokens endpoint to your 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
Available routes:
POST /oauth/token
POST /oauth/revoke
And then protect required endpoints with access_token_required!
method:
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
Take a look at the README for more detailed examples (simple one and customizable).
(by Prostakov、HashDog Team、Vladimir Victorovich)