local-ch / lhs

⚛️ REST services accelerator: Rails gem providing an easy, active-record-like interface for http (hypermedia) json services
GNU General Public License v3.0
137 stars 3 forks source link

Automatic OAuth Authentication #380

Closed 10xSebastian closed 4 years ago

10xSebastian commented 4 years ago

This PR introduces official automatic OAuth authentication.

Adding authentication to all kind of requests made with LHS was the #1 on the annoyance list, when it comes to LHS, often leading people to come up with proxy methods, shared auth options, or storing thread variables themselves, all of it ending up in additional boilerplate code that could've been avoided . Well this PR is gonna take care of it.

Automatic Authentication (OAuth)

LHS provides a way to have records automatically fetch and use OAuth authentication when performing requests within Rails.

In order to enable automatic oauth authentication, perform the following steps:

  1. Make sure LHS is configured to perform auto_oauth. Provide a block that, when executed in the controller context, returns a valid access_token/bearer_token.
    
    # config/initializers/lhs.rb

LHS.configure do |config| config.auto_oauth = -> { access_token } end


2. Opt-in records requiring oauth authentication:

```ruby
# app/models/record.rb

class Record < LHS::Record
  oauth
  # ...
end
  1. Include the LHS::OAuth context into your application controller:
# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  include LHS::OAuth

  # ...
end
  1. Make sure you have the LHC::Auth interceptor enabled:
# config/initializers/lhc.rb

LHC.configure do |config|
  config.interceptors = [LHC::Auth]
end

Now you can perform requests based on the record that will be auto authenticated from now on:

# app/controllers/some_controller.rb

Record.find(1)
https://records/1
Authentication: 'Bearer token-12345'

Configure multiple auth providers (even per endpoint)

In case you need to configure multiple auth provider access_tokens within your application, make sure you provide a proc returning a hash when configuring auto_oauth, naming every single provider and the responsive method to retrieve the access_tokens in the controller context:

# config/initializers/lhs.rb
LHS.configure do |config|
  config.auto_oauth = proc do
    {
      provider1: access_token_provider_1,
      provider2: access_token_provider_2
    }
  end
end

Then make sure you either define which provider to use on a record level:

# model/record.rb
class Record < LHS::Record
  oauth(:provider1)
  #...
end

or on an endpoint level:

# model/record.rb
class Record < LHS::Record
  endpoint 'https://service/records', oauth: :provider1
  #...
end