Ruby on Rails 4: Extract Oauth2 parameters from token response? - ruby-on-rails

I am developing a rails application which uses oauth2 gem to Authenticate a User against Windows azure AD .
I am able to authenticate the user with Azure AD ,but my problem is i need to extract the parameters inside token response.
#token = client.auth_code.get_token(params[:code], :redirect_uri => "#{APP_URL}/callback", :resource => "#{RES_URL}")
I tried puts #token in controller but i am getting some Hash values.
#<OAuth2::AccessToken:0x000000030ed960>
Is it possible to see the contents inside #token.
And also can i set headers inside token request.
#token = client.auth_code.get_token(params[:code], :redirect_uri => "#{APP_URL}/callback", :resource => "#{RES_URL}",:headers => {'Content-Type' => 'application/json' })
Any help is appreciated.

Yo can try to use puts #token.to_yml
to see the contents of #token

Related

AuthenticationError.OAUTH_TOKEN_INVALID

I am trying to access Google Adword's api through google's gem google-api-ads-ruby. I was able to oauth in perfectly fine and grabbed the access token, refresh token, and id_token fine. When I try to access the data it gives me the oauth token invalid error. I retrieved my access token and inputed it on this link and it returned me a valid result.
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=[TOKEN]
The code below is how I am trying to access the Report Definition Service.
config = {
:authentication => {
:method => 'OAuth2',
:oauth2_client_id => #plugin.oauth_client_id,
:oauth2_client_secret => #plugin.oauth_client_secret,
:developer_token => #plugin.developer_token,
:client_customer_id => #plugin.client_customer_id,
:oauth2_token => {"access_token"=>ACCESSTOKEN,
"refresh_token"=>REFRESHTOKEN,
"issued_at"=>"2017-09-18T16:36:55.973-04:00",
"expires_in"=>3600,
"id_token"=>IDTOKEN,
:user_agent => 'Example'
},
:service => {
:environment => 'PRODUCTION'
}
}
api = AdwordsApi::Api.new(config)
report_def_srv = api.service(:ReportDefinitionService, :v201708)
report_type = "ACCOUNT_PERFORMANCE_REPORT"
This code below causes the error
fields = report_def_srv.get_report_fields(report_type)
Why do I keep getting the oauth token is invalid error when it hasn't expired yet?
If the question is still actual..
Try to replace
"expires_in"=>3600
field with
"expires_at"=>"2017-09-18T17:36:55.973-04:00"
It helped to resolve the similar issue in my case.

Ruby on Rails - SoundCloud OAuth 2 undefined method `access_token'

I am working on a making a personal soundcloud app on Rails 5 and i'm having some trouble with OAuth. I'm able to redirect to Soundcloud's app and give permission to my user. When I try to exchange the code for token on redirect_uri, get an error. I have included my code and image of the error I'm getting below.
def connected
client = Soundcloud.new(:client_id => 'My ID',
:client_secret => 'my secret',
:redirect_uri => "http://localhost:3000/login/soundcloud/callback")
code = params[:code]
value = client.exchange_token(:code => code) #get an error on this line
#my code to save access token into db goes here.
end
I have added this image
for the error that I'm getting. I thought it might be more helpful.
I was having the same issues, so I just did created the request manually for this step. Soundcloud gem is pretty dated, I'm sure it has something to do with that.
#client = Soundcloud.new(client_id: client_id,
client_secret: client_secret,
redirect_uri:'http://localhost:3000/soundcloud/connected')
#code = params[:code]
response = HTTParty.post("https://api.soundcloud.com/oauth2/token",
body: {
"client_id" => client_id,
"client_secret" => client_secret,
"redirect_uri" => 'http://localhost:3000/soundcloud/connected',
'grant_type'=> 'authorization_code',
"code" => #code
}
)
access_token = response["access_token"]
#authed_client = Soundcloud.new(access_token: access_token)
soundcloud_user = #authed_client.get('/me')
end
Hope this helps.

Can I send requests to app with devise without credentials?

I have backend app with devise and a ionic app from which I make requests to backend.
Whenever I send requests, gets me 401 status unauthorized.
In this project I've already doorkeeper to manage authorization, so I don't rly need authorization from devise. Can I somehow make these requests( add something to headers ) always authorized without sending post request with credentials?
You need to identify the user somehow. If you're not using a session, you'll need to generate some kind of access token, which Doorkeeper can do for you. I'm not sure if this is helpful or not, but I set up the following flow recently.
One option when using OAuth2 through a trusted client, e.g. a front-end app you build/distribute yourself, is the Resource Owner Password Credentials Grant. Doorkeeper has a guide in the docs for this with advice on dealing with Devise.
I ended up with something like this in my Doorkeeper initializer. You don't need to authorize the client, because you trust it:
resource_owner_from_credentials do |routes|
request.params[:user] = {:email => request.params[:email], :password => request.params[:password]}
request.env['devise.allow_params_authentication'] = true
request.env['warden'].authenticate!(:scope => :user)
end
skip_authorization do |resource_owner|
true
end
Then you should be able to send a request using the password grant type as follows (also shown in the docs).
RestClient.post 'http://localhost:3000/oauth/token', {grant_type: 'password', email: 'email#gmail.com', password: 'password'}, {:accept => 'application/json'}
You should receive the same JSON back as shown in the docs.
{
"access_token": "1f0af717251950dbd4d73154fdf0a474a5c5119adad999683f5b450c460726aa",
"token_type": "bearer",
"expires_in": 7200
}
Now you have a way of identifying your user. You just attach this token to each request to endpoints protected by doorkeeper_for.
RestClient.get 'http://localhost/api/v1/users', { 'Authorization' => 'Bearer 1f0af717251950dbd4d73154fdf0a474a5c5119adad999683f5b450c460726aa', :accept => 'application/json'}

"Missing authorization code" error when trying to use Google Calendar API

The following is the code I am using to allow users to allow users to authorise my app to access their Google Calendar via OAuth. I based it off this sample code.
It works most of the time, but sometimes, there is an ArgumentError: Missing authorization code error on the client.authorization.fetch_access_token! line in the create_google_calendar action in the services controller. If I comment out that line, all of the client.authorization attributes are null.
I am using Rails 3.2.0 and Ruby 1.9.2.
What is causing this?
Gemfile
gem 'google-api-client', :require => 'google/api_client'
service.rb
def self.google_calendar_client google_calendar_service=nil
client = Google::APIClient.new
client.authorization.client_id = xxx
client.authorization.client_secret = xxx
client.authorization.scope = 'https://www.googleapis.com/auth/calendar'
url_prefix = Rails.env.production? ? xxx : 'http://localhost:3000'
client.authorization.redirect_uri = "#{url_prefix}/create_google_calendar"
if google_calendar_service.present?
client.authorization.update_token! :access_token => google_calendar_service.token, :refresh_token => google_calendar_service.google_calendar_refresh_token, :expires_in => google_calendar_service.google_calendar_expires_in, :issued_at => Time.at(google_calendar_service.google_calendar_issued_at)
client.authorization.fetch_access_token! if client.authorization.expired?
end
client
end
services_controller.rb
def connect_google_calendar
#google_calendar_url = Service.google_calendar_client.authorization.authorization_uri.to_s
end
def create_google_calendar
client = Service.google_calendar_client
client.authorization.code = params[:code]
client.authorization.fetch_access_token!
current_user.services.create :provider => 'google_calendar', :token => client.authorization.access_token, :google_calendar_refresh_token => client.authorization.refresh_token, :google_calendar_expires_in => client.authorization.expires_in, :google_calendar_issued_at => client.authorization.issued_at
end
The truth is, I don't know. Your code looks right to me. But I can at least tell you what the error means. Missing authorization code means that it thinks you're trying to do an "authorization code" grant type when you fetch the access token. If you're actually trying to obtain an access token off a refresh token as opposed to doing it on the first pass after obtaining authorization from the user, then you may not have correctly set up the authorization object.
You can check this by inspecting the client.authorization.grant_type value. In very recent versions of the client you can manually set the grant_type value to force a particular mode, which may give you more informative error messages, depending on what the actual issue is.

how to get oauth access token for facebook using ruby

Am trying to get oauth access token for facebook programmatically in ruby.
My code is as follows:
client = OAuth2::Client.new(
APP_ID,
SECRET_ID,
:authorize_url => "/dialog/oauth",
:token_url => "/oauth/access_token",
:site => "https://www.facebook.com/"
)
code = client.auth_code.authorize_url(:redirect_uri => "http://www.facebook.com/")
token = client.auth_code.get_token(code, :redirect_uri => "https://graph.facebook.com/")
OAuth2::AccessToken.new(client, token.token, {:mode => :query, :param_name =>"oauth_token"})
When i try to run the above ruby code, i'm getting the following exception
https://www.facebook.com/dialog/oauth?response_type=code&client_id=APP_ID
51&redirect_uri=http%3A%2F%2Fwww.facebook.com%2F
/home/ec2-user/.rvm/gems/ruby-1.9.3-p0#samples/gems/oauth2-0.5.2/lib/oauth2/clie
nt.rb:129:in `get_token': OAuth2::Error (OAuth2::Error)
from /home/ec2-user/.rvm/gems/ruby-1.9.3-p0#samples/gems/oauth2-0.5.2/li
b/oauth2/strategy/auth_code.rb:29:in `get_token'
from oauth.rb:16:in `<main>'
Any help is greatly appreciated as I have spent more than a day while trying to sort this out.
Have you tried to put as redirect_uri instead of localhost:3000 your real IP address ex. 231.61.233.57:3000? Additionally you could try to use ssh tunneling for testing purposes so your localhost application will be available worldwide. Check this out http://progrium.com/localtunnel/ .
When you will get ip address from this tool try to set redirect_uri param to it.

Resources