How do you get the data from the access token? It looks like I get the data encrypted. Do I need an key to decrypt it? Here's the sample of the code.
x = Net::HTTP.post_form(URI.parse('http://www.asite.com/getinfo'), params)
#response = ActiveSupport::JSON.decode(x.body)
%>
<b>Got access token and access token is:</b><br>
<%=#response['access_token'] %>
Use the JWT ruby gem
x = Net::HTTP.post_form(URI.parse('http://somesite.com/get_token'), params)
#res = ActiveSupport::JSON.decode(x.body)
id_token = #res['id_token']
id_data = JWT.decode id_token, 'secret', false
Related
I am trying to work with the Google Calendar API in my Rails(5.2.1) app but am having real trouble with the refresh token--my understanding of which is tenuous at best, even after having gone through quite a bit of documentation.
Here is my code:
class CalendarsController < ApplicationController
def authorize
client = Signet::OAuth2::Client.new(client_options)
redirect_to client.authorization_uri.to_s
end
def callback
client = Signet::OAuth2::Client.new(client_options)
client.code = params[:code]
response = client.fetch_access_token!
session[:authorization] = response
redirect_to root_url
end
def get_calendars
client = Signet::OAuth2::Client.new(client_options)
client.update!(session[:authorization])
client.update!(
additional_parameters: {
access_type: 'offline',
prompt: 'consent'
}
)
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = client
# here is my attempt to refresh
begin
service.list_calendar_lists
rescue Google::Apis::AuthorizationError
response = client.refresh!
session[:authorization] = session[:authorization].merge(response)
retry
end
end
def new
all_calendars = get_calendars.items
#calendar_list = all_calendars.select {|calendar| calendar.access_role=="owner"}
end
def client_options
{
client_id: Rails.application.credentials.web[:client_id],
client_secret: Rails.application.credentials.web[:client_secret],
authorization_uri: 'https://accounts.google.com/o/oauth2/auth?access_type=offline&prompt=consent',
token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
scope: Google::Apis::CalendarV3::AUTH_CALENDAR,
redirect_uri: callback_url
}
end
end
If I go to the URL that leads to #authorize I am directed to an OAuth screen and asked for permission to access my calendars. Once granted, the app works as expected. After an hour, the token expires and I can't get it to refresh. You can see my attempt above: Without that attempt, I get a Google::Apis::AuthorizationError. With it, I get "Missing authorization code." I'm totally lost and am having trouble following the documentation.
The documentation is quite challenging, and the error messages don't help much!
You're not showing the client_options that are being passed in, and since everything else looks correct - I'm guessing this is where the problem lies. Are you setting the access_type parameter for offline access, so that you can actually refresh the token without the user having to re-authenticate?
From the documentation:
Set the value to offline if your application needs to refresh access
tokens when the user is not present at the browser. This is the method
of refreshing access tokens described later in this document. This
value instructs the Google authorization server to return a refresh
token and an access token the first time that your application
exchanges an authorization code for tokens.
You can do this in the authorization_uri. For example:
client = Signet::OAuth2::Client.new({
client_id: ...,
client_secret: ...,
authorization_uri: "https://accounts.google.com/o/oauth2/auth?access_type=offline&prompt=consent",
scope: Google::Apis::CalendarV3::AUTH_CALENDAR,
redirect_uri: callback_url
})
Or when calling update!:
client.update!(
additional_parameters: {
access_type: 'offline',
prompt: 'consent'
}
)
I am new to use gem devise_token_auth and working on a mobile client api, two questions:
1) How should i identify a user? My current understanding is on a http request header set access_token is this right?
But seems from the source code i should provide for uid, access_token, clientlink
uid = request.headers['did']
#token = request.headers['access-token']
#client_id = request.headers['client']
2) i can find a user.tokens like below:
{"AOYZdDmwI7WQr8I6T4PpPw"=>{"token"=>"$2a$10$C/5f3JV7.9DZG8w.ggdCPelB6kzitWuGK4rfozHv15Hhf/x9DaCcO", "expiry"=>1473485374, "last_token"=>"$2a$10$abctsIP5bHPIm2nMXFTUH.1jPWQ5LiGTTrENjoqihWgcCkwRqbxb6", "updated_at"=>"2016-08-27T13:29:34.948+08:00"}}
which is client and which is access-token?
Thank you!
headers = JSON.parse(cookies['authHeaders'])
uid = headers['uid']
token = headers['access-token']
client_id = headers['client']
user = User.find_by_uid(uid)
if !user || !user.valid_token?(token, client_id)
render json: {error: "Usuario no autorizado."}, status: 401
end
I am using omniauth-oauth2 in rails to authenticate to a site which supports oauth2. After doing the oauth dance, the site gives me the following, which I then persist into the database:
Access Token
Expires_AT (ticks)
Refresh token
Is there an omniauth method to refresh the token automatically after it expires or should I write custom code which to do the same?
If custom code is to be written, is a helper the right place to write the logic?
Omniauth doesn't offer this functionality out of the box so i used the previous answer and another SO answer to write the code in my model User.rb
def refresh_token_if_expired
if token_expired?
response = RestClient.post "#{ENV['DOMAIN']}oauth2/token", :grant_type => 'refresh_token', :refresh_token => self.refresh_token, :client_id => ENV['APP_ID'], :client_secret => ENV['APP_SECRET']
refreshhash = JSON.parse(response.body)
token_will_change!
expiresat_will_change!
self.token = refreshhash['access_token']
self.expiresat = DateTime.now + refreshhash["expires_in"].to_i.seconds
self.save
puts 'Saved'
end
end
def token_expired?
expiry = Time.at(self.expiresat)
return true if expiry < Time.now # expired token, so we should quickly return
token_expires_at = expiry
save if changed?
false # token not expired. :D
end
And before making the API call using the access token, you can call the method like this where current_user is the signed in user.
current_user.refresh_token_if_expired
Make sure to install the rest-client gem and add the require directive require 'rest-client' in the model file. The ENV['DOMAIN'], ENV['APP_ID'] and ENV['APP_SECRET'] are environment variables that can be set in config/environments/production.rb (or development)
In fact, the omniauth-oauth2 gem and its dependency, oauth2, both have some refresh logic built in.
See in https://github.com/intridea/oauth2/blob/master/lib/oauth2/access_token.rb#L80
# Refreshes the current Access Token
#
# #return [AccessToken] a new AccessToken
# #note options should be carried over to the new AccessToken
def refresh!(params = {})
fail('A refresh_token is not available') unless refresh_token
params.merge!(:client_id => #client.id,
:client_secret => #client.secret,
:grant_type => 'refresh_token',
:refresh_token => refresh_token)
new_token = #client.get_token(params)
new_token.options = options
new_token.refresh_token = refresh_token unless new_token.refresh_token
new_token
end
And in https://github.com/intridea/omniauth-oauth2/blob/master/lib/omniauth/strategies/oauth2.rb#L74 :
self.access_token = access_token.refresh! if access_token.expired?
So you may not be able to do it directly with omniauth-oauth2, but you can certainly do something along the lines of this with oauth2:
client = strategy.client # from your omniauth oauth2 strategy
token = OAuth2::AccessToken.from_hash client, record.to_hash
# or
token = OAuth2::AccessToken.new client, token, {expires_at: 123456789, refresh_token: "123"}
token.refresh!
Eero's answer unlocked a path for me to solve this. I have a helper concern for my classes which get me a GmailService. As part of this process, the user object (which contains the google auth info) gets checked if it's expired. If it has, it refreshes before returning the service.
def gmail_service(user)
mail = Google::Apis::GmailV1::GmailService.new
# Is the users token expired?
if user.google_token_expire.to_datetime.past?
oauth = OmniAuth::Strategies::GoogleOauth2.new(
nil, # App - nil seems to be ok?!
"XXXXXXXXXX.apps.googleusercontent.com", # Client ID
"ABC123456" # Client Secret
)
token = OAuth2::AccessToken.new(
oauth.client,
user.google_access_token,
{ refresh_token: user.google_refresh_token }
)
new_token = token.refresh!
if new_token.present?
user.update(
google_access_token: new_token.token,
google_token_expire: Time.at(new_token.expires_at),
google_refresh_token: new_token.refresh_token
)
else
puts("DAMN - DIDN'T WORK!")
end
end
mail.authorization = user.google_access_token
mail
end
There is some information here, too much to list here. It may depend on the provider you are using, and their allowed usage of the refresh-token
Similarly to other answers I followed this approach, where the model storing the auth and refresh tokens is used, abstracting API interactions from that logic.
See https://stackoverflow.com/a/51041855/1392282
If you are using devise you can create a new strategy the following way I guess, so that you don't need to repeat client id and secret everywhere:
# first argument is something called app, but not sure what but nil seems to be fine.
Strategies::MyStrategy.new(nil, *Devise.omniauth_configs[:mystrategy].args)
I am hoping someone with more experience can help me get my head round this Google API.
I am just building a demo app based off the ruby quickstart sample app, to explore this API. I have a Rails 4.0 app and have successfully (for the most part) installed the Google+ sign in.
It all goes wrong though once the access token for the user expires.
What my test app does successfully:
Signs the user in and retrieves access token for client side along with server code.
Exchanges the server code for access token & refresh token & id token
Creates token pair object that holds access token and refresh token, then stores it in a session hash
My app can then make requests to get user people list, insert moments etc.
So my question is, what is the correct way to get a new access token with the refresh token?
With the code below, after the access token expires I get error of "Invalid Credentials"
If I call $client.authorization.refresh! then I get error of "Invalid Request"
config/initializers/gplus.rb
# Build the global client
$credentials = Google::APIClient::ClientSecrets.load
$authorization = Signet::OAuth2::Client.new(
:authorization_uri => $credentials.authorization_uri,
:token_credential_uri => $credentials.token_credential_uri,
:client_id => $credentials.client_id,
:client_secret => $credentials.client_secret,
:redirect_uri => $credentials.redirect_uris.first,
:scope => 'https://www.googleapis.com/auth/plus.login',
:request_visible_actions => 'http://schemas.google.com/AddActivity',
:accesstype => 'offline')
$client = Google::APIClient.new(application_name: " App", application_version: "0.1")
*app/controllers/google_plus_controller.rb*
class GooglePlusController < ApplicationController
respond_to :json, :js
def callback
if !session[:token]
# Make sure that the state we set on the client matches the state sent
# in the request to protect against request forgery.
logger.info("user has no token")
if session[:_csrf_token] == params[:state]
# Upgrade the code into a token object.
$authorization.code = request.body.read
# exchange the one time code for an access_token, id_token and refresh_token from Google API server
$authorization.fetch_access_token!
# update the global server client with the new tokens
$client.authorization = $authorization
# Verify the issued token matches the user and client.
oauth2 = $client.discovered_api('oauth2','v2')
tokeninfo = JSON.parse($client.execute(oauth2.tokeninfo,
:access_token => $client.authorization.access_token,
:id_token => $client.authorization.id_token).response.body)
# skipped
token_pair = TokenPair.new
token_pair.update_token!($client.authorization)
session[:token] = token_pair
else
respond_with do |format|
format.json { render json: {errors: ['The client state does not match the server state.']}, status: 401}
end
end # if session csrf token matches params token
# render nothing: true, status: 200
else
logger.info("user HAS token")
end # if no session token
render nothing: true, status: 200
end #connect
def people
# Check for stored credentials in the current user's session.
if !session[:token]
respond_with do |format|
format.json { render json: {errors: ["User is not connected"]}, status: 401}
end
end
# Authorize the client and construct a Google+ service
$client.authorization.update_token!(session[:token].to_hash)
plus = $client.discovered_api('plus', 'v1')
# Get the list of people as JSON and return it.
response = $client.execute!(api_method: plus.people.list, parameters: {
:collection => 'visible',
:userId => 'me'}).body
render json: response
end
#skipped
end
Any help appreciated. Extra questions, the sample app I'm using as a guide builds a global authorization object (Signet::OAuth2::Client.new) - however other documentation I have read over the last day has stated building an authorization object for each API request. Which is correct?
This is a fragment I use in an app:
require 'google/api_client'
if client.authorization.expired? && client.authorization.refresh_token
#Authorization Has Expired
begin
client.authorization.grant_type = 'refresh_token'
token_hash = client.authorization.fetch_access_token!
goog_auth.access_token = token_hash['access_token']
client.authorization.expires_in = goog_auth.expires_in || 3600
client.authorization.issued_at = goog_auth.issued_at = Time.now
goog_auth.save!
rescue
redirect_to user_omniauth_authorize_path(:google_oauth2)
end
I am using omniauth OAuth2 (https://github.com/intridea/omniauth-oauth2), omniauth-google-oauth2 (https://github.com/zquestz/omniauth-google-oauth2), and google-api-ruby-client (https://code.google.com/p/google-api-ruby-client/).
Walk through:
1) If the access token is expired & I have a refresh token saved in the DB, then I try a access token refresh.
2) I set the grant type to "refresh_token" & then the "fetch_access_token!" call returns a plain old hash.
3) I use the 'access_token' key to return the new valid access token. The rest of the key/values can pretty much be ignored.
4) I set the "expires_in" attr to 3600 (1hr), and the "issued_at" to Time.now & save.
NOTE: Make sure to set expires_in first & issued_at second. The underlying Signet OAuth2 client resets your OAuth2 client issued_at value to Time.now, not the value you set from the DB, and you will find that all calls to "expired?" return false. I will post Signet source at the bottom.
5) If the access code is expired and I do NOT have a refresh token, I redirect to the omniauth path, and start the whole process over from scratch, which you have already outlined.
Note: I save almost everything in the DB: access_token, refresh_token, even the auth_code. I use the figaro gem to save env specific values such as client_id, client_secret, oauth2_redirect, and things like that. If you use multiple env's to develop, use figaro (https://github.com/laserlemon/figaro).
Here is the Signet source that shows how setting expires_in manually actually resets issued_at to Time.now(!). So you need to set "expires_in" first & THEN "issued_at" using the issued_at value you have from the DB. Setting expires_in second will actually RESET your issued_at time to Time.now... eg; calls to "expired?" will ALWAYS return false!
How do I know this? As Mr T would say, "Pain."
http://signet.rubyforge.org/api/Signet/OAuth2/Client.html#issued_at%3D-instance_method
# File 'lib/signet/oauth_2/client.rb', line 555
def expires_in=(new_expires_in)
if new_expires_in != nil
#expires_in = new_expires_in.to_i
#issued_at = Time.now
else
#expires_in, #issued_at = nil, nil
end
The line saying:
accesstype => 'offline'
should say:
access_type => 'offline'
I am working on integrating Omniauth with my new Facebook application, and I am looking through the rather sparse documentation to understand if it gives simple ways to access the graph API... I am moving from Koala which was pretty simple.
Has anyone out there used Omniauth for this yet? I want to get photos from the users' albums, and sort and get the unique URLs for them.
I finally found out:
1) include this gem
2) use the gem:
user = FbGraph::User.new('me', :access_token => session[:omniauth]["credentials"]["token"])
user.fetch
3) retrieve your information
user.name
Remember you can get anything from here ttp://developers.facebook.com/docs/reference/api/user
Another good option is Koala: https://github.com/arsduo/koala
If you're just using Facebook, Koala has its own OAuth support. It also works fine with OmniAuth. To use them together, set up OmniAuth per this Railscast:
http://railscasts.com/episodes/235-omniauth-part-1
Then add a 'token' column to 'authentications' table, and any supporting methods for retrieving tokens. When the app needs to interact with Facebook, let Koala grab the token and do its thing. In a controller:
if #token = current_user.facebook_token
#graph = Koala::Facebook::GraphAPI.new(#token)
#friends = #graph.get_connections("me", "friends")
end
First, I would go for fb_graph, just compare:
with koala:
graph = Koala::Facebook::GraphAPI.new OAUTH_ACCESS_TOKEN
friends = graph.get_connections("me", "friends")
graph.put_object("me", "feed", :message => "I am writing on my wall!")
with fb_graph:
me = FbGraph::User.me OAUTH_ACCESS_TOKEN
my_friends = me.friends
me.feed! :message => "I am writing on my wall!"
When using omniauth, every user has many authorizations (facebook, twitter, ...)
For each user authorization, you should store the oauth token that is returned in your oauth callback hash.
auth = Authorization.create!(:user => user,
:uid => hash['uid'],
:provider => hash['provider'],
:token => hash['credentials']['token'])
Then wherever you want to access albums and photos, do something like this:
class User
...
has_many :authorizations
...
def grap_facebook_albums
facebook = authorizations.where(:provider => :facebook).first
fb_user = ::FbGraph::User.fetch facebook.uid, :access_token => facebook.token
fb_albums = fb_user.albums
end
...
end
So I wasn't able to get fb_graph to work properly - I am still a noob having been a Ruby On Rails developer for a total of about 8-10 weeks, and therefore don't have an instinct for what must be obvious problems to other folks.
However I found this great little blog post which outlines a simple facebook client and shows clearly how it all plugs together. I found an issue with it picking up the me/picture object as Facebook returns an http302 not http200 but that was easily worked around with the help of the author. Check it out: http://bnerd.de/misc/ruby-write-basic-client-for-facebook-graph-api/
I am now using Omniauth for the simplicity of the login/signup interaction based on this walkthrough here: blog.railsrumble.com/blog/2010/10/08/intridea-omniauth and with the token I get from that I am using this simple FBClient from the bnerd reference above to access the Graph API. Hope what I found helps others.
...here's my version of bnerd's code and it worked for me:
class FBClient
def initialize(app, access_token = nil)
#app = app
#access_token = access_token
end
# request permission(s) from user
def request(perms)
#create a random verifier to identify user on fb callback
verifier = (0...10).map{65.+(rand(25)).chr}.join
uri = "https://graph.facebook.com/oauth/authorize?client_id=#{#app.app_id}&redirect_uri=#{#app.connect_url}?verifier=#{verifier}&scope=#{perms}"
request = { :verifier => verifier, :uri => uri }
return request
end
def connect(code, verifier)
uri = URI.parse("https://graph.facebook.com/oauth/access_token?client_id=#{#app.app_id}&redirect_uri=#{#app.connect_url}?verifier=#{verifier}&client_secret=#{#app.secret}&code=#{CGI::escape(code)}")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.path + "?" + uri.query)
response = http.request(request)
data = response.body
return data.split("=")[1]
end
# get, post
def get(path, params = nil)
uri = URI.parse("https://graph.facebook.com/" + path)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
if params.nil?
params = Hash.new
end
if params["access_token"].nil?
params["access_token"] = #access_token unless #access_token.nil?
end
request = Net::HTTP::Get.new(uri.path)
request.set_form_data( params )
request = Net::HTTP::Get.new(uri.path + "?" + request.body)
return response = http.request(request)
end
def post(path, params = nil)
uri = URI.parse("https://graph.facebook.com/" + path)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
if params.nil?
params = Hash.new
end
if params[:access_token].nil?
params[:access_token] = #access_token unless #access_token.nil?
end
request = Net::HTTP::Post.new(uri.path)
request.set_form_data( params )
request = Net::HTTP::Post.new(uri.path + "?" + request.body)
response = http.request(request)
response.code == "200" ? feed = JSON.parse(response.body) : raise("Sorry, an error occured. #{response.body}")
return feed
end
end
I am sure someone more experienced than I could improve this - I was about 10 weeks into learning Ruby (and my first programming since Fortran and Pascal at university in the early 90s!).
I also had problems getting the devise+Omniauth solution to work. I had to problems:
The session cookie did not store the facebook authentication token that is necessary to initialize fb_graph and koala.
I was unable to initialize fb_graph after getting the facebook authentication token in place (but got Koala to work after some work).
I solved #1 by inserting 'session[:omniauth] = omniauth' into the create method of the authentications_controller.rb.
I solved #2 by using Koala. Seem like fb_graph requires oauth2, and the devise omniauth integration use oauth. Koala works with perfectly with the facebook authentication token stored by session[:omniauth]["credentials"]["token"].
You initialize koala like this:
- #fbprofile =
Koala::Facebook::GraphAPI.new(
session[:omniauth]["credentials"]["token"]
)
I made sure oauth and oauth2 were uninstalled, and then I installed oauth2. It appears that now omniauth and fb_graph are working ... but probably need to test it more.