
Imagine that one day you decide to connect oauth2 to your project on ruby on rails. Since the authentication of most rails applications is now going through
devise , it would be nice to integrate oauth2 with this gem. Fortunately, everything came up with us, so
please meet -
devise_oauth2_providable . With this gem, integration and testing of an oauth2 provider takes no more time than going to the store.
So let's get started. Edit the gemfile and add the following line there.
gem 'devise_oauth2_providable'
')
Run the bundle as usual. Next, you need to create a clients label where all the data of oauth clients will be stored. Fortunately, the developers of the heme made sure that we did not have to write the migration with pens
class CreateOauth2Schema < ActiveRecord::Migration def self.up Devise::Oauth2Providable::Schema.up(self) end def self.down Devise::Oauth2Providable::Schema.down(self) end end
In the model that you want to enable to authenticate through oauth2, add the following line:
devise :oauth2_providable, :oauth2_refresh_token_grantable, :oauth2_authorization_code_grantable
That's all. It remains only to test this thing.
For this, too, there is a ready-made thing
devise-oauth2-provider-client , written in Sinatra.
First, let's create a test client in the Client model:
Client.create( :name => "Sinatra Client", :redirect_uri => "http://localhost:9393/oauth/callback", :website => "http://localhost:9393/", :identifier => "120094574673767", :secret => "b54dc82476af2814e620b86776c42c0e" )
Then we clone the repository and set the gems that the application asks for using the bundle.
Next, go to the client folder, edit the get '/ oauth / callback' method. There will need to correct the line
access_token.get('/me').body
And zebenit '/ me', on the page that we give the main application after a successful login. Let this be the main page for the test:
access_token.get('/').body
We start the server:
bundle exec shotgun
On port 9393, the Sinatra server starts.
We go to the
http: // localhost: 9393 / oauth / start page and if everything was done correctly, we will redirect to the 3000th port with the rail application, we confirm access to Sinatra Client, go back already authorized, and the main page of our rail application is shown to us .