I am having trouble connecting a few dots with OAuth and Active Resource. Here is what I know: The Active Resource documentation tells me that I can set authentication tokens on the ActiveResource model itself like so:
ActiveResource::Base.connection.auth_type = :bearer
ActiveResource::Base.connection.bearer_token = @bearer_token
class Estimate < ActiveResource::Base
self.connection.auth_type = :bearer
self.connection.bearer_token = @bearer_token
self.site = "https://apistaging.uship.com/v2/estimate"
end
Also, in a totally seperate part of my code, I can retrieve the bearer token I need with the following basic HTTP requests (omitting my actual client id and secret for privacy sake):
uri = URI('https://apistaging.uship.com/oauth/token')
res = Net::HTTP.post_form(uri, 'grant_type' => 'client_credentials', 'client_id' => 'XXXXXXXXXXXXXXXXXXX', 'client_secret' => 'YYYYYYY')
When I print res, it gives me a valid token, which I have tested. It looks like this:
{
"access_token": "AAAAAAAAAAAAAAAAAAAAA",
"token_type": "bearer",
"expires_in": 600,
"refresh_token": "BBBBBBBBBBBBBBBBBBBBB"
}
But where do I run this call? I am guessing maybe some sort of before_filter on any controllers which will use Active Resource? And if so, how to I pass the access_token to that variable @bearer_token in my ActiveResource model. Also, I know that that access token will expire in 10 minutes, so somehow this code will have to know how to run the oauth token again, at the right times, or pass refresh tokens when Active Resource is being used in less than 10 minute intervals. I am very surprised to not find a simple tutorial for this online. If someone feels I should be using a gem to automate this, let me know which one, because everything I've found doesn't appear to work on rails 5.
If you extend ActiveResource like this https://gist.github.com/acherukuri/0f297e145b8242c2e991647c77f1a91e with https://github.com/oauth-xx/oauth-ruby, you would be able to make calls to your services using the OAuth gem instead of ActiveResource but the response can be handed over to ActiveResource so that you will still be able to rescue errors using
ActiveResource::ServerErrorstyle in your controllers. In this way, your controller will not be polluted with the generation of OAuth tokens and also ActiveResource will generate a new OAuth token only if it's about to expire. (same token will be used for the subsequent calls until it gets expired)