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?
Asked
Active
Viewed 1,775 times
2
-
I'm rather late to the party but doorkeeper may be relevant: https://github.com/doorkeeper-gem/doorkeeper – Amos Joshua Dec 23 '21 at 20:06
2 Answers
0
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).

Vladimir Victorovich
- 21
- 3