I am trying to get a user venue history from foursquare. I know first of all a user should access to my application. I am using OAuth2 gem. How can I get client_id of the user?
cli = OAuth2::Client.new('CLIENT_ID', :authorize_url => "/oauth2/authorize", :token_url => "/oauth2/access_token", :site => 'https://foursquare.com')
ok, I am just editing my question. I understood why client_id has to be used (thanks to Martin and umesh awasthi). I am asking about why I can't get token of a user? my whole code is;
cli = OAuth2::Client.new(client_id, client_secret, :authorize_url => "/oauth2/authorize", :token_url => "/oauth2/access_token", :site => 'https://foursquare.com')
cli.auth_code.authorize_url(:redirect_uri => "http://localhost:3000")
token = cli.auth_code.get_token('authorization_code_value', :redirect_uri => "http://localhost:3000/person/index")
response = token.get('api/resource', :params => {'query_foo' => 'bar'})
response.class.name
See the answer of Martin client id is a unique id associated with your application.All OAuth service provider need this client id to identity yourself.
I suggest you to first go through some basic understanding of OAuth as this protocol work on 2 major things
1. Client_id: this is a unique id assigned to your application you
create on any Oauth service provider or when you register you application.
2. Secret_key:This is another part of Oauth communication which use to
Authenticate the consumer i.e you application.
Though some Oauth system like Google provides Anonymous calling but that never being encouraged at all.
So whatever OAuth service you are using, you need to register your application with them and get client_key and secret which should be the part of every communication you making with OAuth
here is the quick steps taken from forsquare website
Redirect users who wish to authenticate to
https://foursquare.com/oauth2/authenticate
?client_id=YOUR_CLIENT_ID
&response_type=code
&redirect_uri=YOUR_REGISTERED_REDIRECT_URI
If a user accepts, they will be redirected back to
https://YOUR_REGISTERED_REDIRECT_URI/?code=CODE
once user authorize you OAuth will redirect back with the code which you need to pass them again to get access token
Your server will make a request for
https://foursquare.com/oauth2/access_token
?client_id=YOUR_CLIENT_ID
&client_secret=YOUR_CLIENT_SECRET
&grant_type=authorization_code
&redirect_uri=YOUR_REGISTERED_REDIRECT_URI
&code=CODE
The response will be JSON
{ access_token: ACCESS_TOKEN }
Save this access token for this user in your database.Hope this swill help you
The client_id is the client_id for your application, which you get when you register an app here. It is not associated with a particular user, but with your application.
Related
We are migrating a large enterprise application from the Google Contacts API to the People API.
Before, using the OAuth token to make requests to the Contacts API was easy. We would authenticate with OAuth, and then pass the token to the Google Contacts API like so:
# access_token is the token we receive from OAuth
#user = GoogleContactsApi::User.new(access_token)
# make a request
contact_objects = user.contacts
The PeopleService code shows how to use an API key, and then only makes mention of the OAuth token:
# API key. Your API key identifies your project and provides you with API access,
# quota, and reports. Required unless you provide an OAuth 2.0 token
But I've been unable to find an example of how to use the OAuth token to make requests to the People API using the Ruby gem.
Could you please provide a simple example of how to make a People API request using the OAuth token? Specifically, we want access to a user's contacts' email address and phone numbers. I believe we will be using get_people. If you could provide this specific example, that would be wonderful.
Thank you! 😄
It looks like we needed to access access_token.token and set it like so:
require 'google/apis/people_v1'
class GooglePeopleApiWrapper
attr_reader :service, :access_token
def initialize(oauth_object)
# outh_object is the `access_token` from my question, which is
# provided in the OAuth response
#oauth_object = oauth_object
#service = Google::Apis::PeopleV1::PeopleServiceService.new
#service.authorization = #oauth_object.token
end
def fetch_contacts
# Fetch the next 10 events for the user
contact_objects = #service.list_person_connections(
'people/me',
page_size: 10,
person_fields: 'names,emailAddresses,phoneNumbers',
)
etc...
end
end
I am using Ruby on Rails 5.2 and gems: ruby-trello, devise, omniauth-trello.
I want to make authorized requests on behalf of Trello user same as shows here: https://github.com/jeremytregunna/ruby-trello#multiple-users
Example from git docs:
#client_bob = Trello::Client.new(
:consumer_key => YOUR_CONSUMER_KEY,
:consumer_secret => YOUR_CONSUMER_SECRET,
:oauth_token => "Bob's access token",
:oauth_token_secret => "Bob's access secret"
)
My steps:
User (Bob) sign in with Trello and get his own oauth_secret and oauth_token
App creates a Trello::Client for Bob using:
his own oauth data (:oauth_token, :oauth_token_secret)
I got consumer_key from here: https://trello.com/app-key (in the top of page, first block with key field)
consumer_secret was taken from https://trello.com/app-key too, but from the bottom of page, last block with key secret
After this, I'm trying to get any data from Bob's trello account (boards, lists, tasks etc.) but always getting 500 error (invalid token).
Could you explain what I'm doing wrong?
Thank you in advance.
What I did was implementing a session controller to request and authorize access to user's trello and then call Trello::Client with the authorization params inside the callback method on the controller.
Check out this:Trello OAuth 1.0 authorization with Ruby
Then inside the authorization method you can call Trello::Client using :oauth_token and :oauth_token_secret from get_access_token call or store them both on the session object and use them anywhere.
I am attempting to access the Office 365 API from a Ruby on Rails backend and am having problems.
Whether I use the ruby_outlook gem (github) or follow Microsoft's official Ruby on Rails sample, I am getting 401 unauthorized.
My access_token is being saved using Omniauth and is valid, I checked by pasting it in here.
Am I using the correct access_token? It is over 1400 characters long (1442 to be exact). Can anyone show me an example of how to properly call the Office 365 Mail API from Ruby?
Code Example (using Faraday):
key = #auth[:key]
conn = Faraday.new(:url => 'https://outlook.office.com') do |faraday|
# Outputs to the console
faraday.response :logger
# Uses the default Net::HTTP adapter
faraday.adapter Faraday.default_adapter
end
response = conn.get do |request|
request.url '/api/v2.0/me/contacts'
request.headers['Authorization'] = "Bearer #{key}"
request.headers['Accept'] = 'application/json'
end
Code Example (using ruby_outlook gem):
client = RubyOutlook::Client.new
key = #auth[:key]
page = 1
view_size = 30
fields = [
'DisplayName',
'EmailAddresses'
]
sort = {:sort_field => 'DisplayName', :sort_order => 'ASC'}
contacts = client.get_contacts key, view_size, page, fields, sort
The exact error that the ruby_outlook gem returns is:
{"ruby_outlook_error"=>401}
The problem is a mismatch between the scopes in your token and the API endpoint you're using. The scope has to match the endpoint.
In your case, you requested a Graph API scope, but you're calling the Outlook API endpoint.
You should only have to register in one place for your client ID and secret: https://apps.dev.microsoft.com. It sounds like you may have also registered an app in the Azure Management Portal (which requires you to specify scopes in the registration itself).
Make sure you're using a client ID from apps.dev.microsoft.com and make sure your scopes are requested as 'https://outlook.office.com' scopes, and you should be good to go.
That Omniauth strategy might require that you register in the Azure Management Portal if they are dependent on Azure's v1 auth endpoints. In that case, forget what I said about apps.dev.microsoft.com and instead change your app registration to use the appropriate permissions from Microsoft Exchange Online.
UPDATE: Based on your comments, that Omniauth strategy DOES require the v1 Azure auth/token endpoints, so you have 2 options if you want to keep using that strategy:
Change your code to use the Graph endpoints. You'll need to use the Faraday option above (ruby_outlook is designed for the Outlook endpoints), and change your URL to https://graph.microsoft.com, and the request.url to /v1.0/me/contacts.
Create a new app registration at https://dev.outlook.com/appregistration, which will create the proper scopes for your code. You'll need an Office 365 account to login to the app registration tool.
I am using the Facebook Graph API in my rails projects, no matter I use oauth2 gem or koala, It need callback_url
Oauth2
token = client.auth_code.get_token('code_value', :redirect_uri => 'http://localhost:8080/oauth/callback')
Koala
#oauth = Koala::Facebook::OAuth.new(app_id, app_secret, callback_url)
I try to use http://localhost:3000/callback in my project, but it's not working.
Should I develop a routes for that?
like: get 'callback' => 'oauth#callback'?
What should I write in the callback method in OauthController, what does it use for? Thanks
Yes, you should.
Basically, OAuth uses callback data to provide tokens for authenticating users.
For example
user clicks on "sign in" (or whatever) link and your app redirects they to the OAuth provider (or open it in the iframe).
user permits to your app to use they profile details
OAuth provider send callback to your app with unique code
app uses that code to get secure access token for API communications
That's just a basic example.
In your case you need to implement controller that will parse callback data.
Here is the code example
#oauth = Koala::Facebook::OAuth.new(api_key, app_secret, callback_url)
=> #<Koala::Facebook::OAuth:0x007fc919d014e0 #app_id=1234567890, #app_secret="FaKeAppSecretKey", #oauth_callback_url="http://localhost:3000/callback">
#oauth.url_for_oauth_code
=> "https://www.facebook.com/dialog/oauth?client_id=893637180663238&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback"
And when you go to https://www.facebook.com/dialog/oauth?client_id=893637180663238&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback FB will redirect you to
http://localhost:3000/callback?code=CODE_FROM_CALLBACK
Then you should use implement controller that uses code to get access token
access_token = #oauth.get_access_token(params[:code])
=> "ACCESS_TOKEN"
#graph = Koala::Facebook::API.new(access_token)
=> #<Koala::Facebook::API:0x007fc91a903ae0 #access_token="ACCESS_TOKEN", #app_secret=nil>
profile = #graph.get_object("me")
=> {"id"=>"4492344324865", "email"=>"my_fake_email_address#gmail.com", "first_name"=>"Roman", "gender"=>"male", "last_name"=>"Sotnikov", "link"=>"https://www.facebook.com/app_scoped_user_id/4492344324865/", "locale"=>"en_US", "name"=>"Roman Sotnikov", "timezone"=>6, "updated_time"=>"2015-05-18T05:19:54+0000", "verified"=>true}
Please check https://github.com/arsduo/koala/wiki/OAuth for additional info.
Callback Url is yours applications url -- a GET route -- you want the third party application to redirect to, after its done its work.
So in your routes.rb file simply create a get route
get 'facebook_graph_callback', to: 'controller_name#action'
#A get route which is connected to a controller action
Usually the third party will give you some sort of information back. Quite often its some sort of code. In your controller action you can use find them in params hash.
I have a service account and I am using the OAuth2 gem together with the Google API Ruby Client:
require 'oauth2'
require 'google/api_client'
My objective is to fetch an access token which allows access to a specific user’s account and no other. I think this is often achieved using the sub parameter when using HTTP, but how do I do this using the Ruby client libraries above?
I can get an access token successfully and use it to access the drive v2 file list API. I always see a single "How to get started with Drive" document in the response and no other.
I suspect my attempt to impersonate a user has not succeeded. Basically I’m passing in an email address as a sub option to the function below:
client = Google::APIClient.new(...)
access_token = OAuth2::AccessToken.new(oauth2_client, client.authorization.access_token, {‘sub’ => ‘user#domain.com’} )
Presumably that isn’t the way to do this.
How to I retrieve an access token which is scoped to permit access impersonating a single user and no other?
Following Steve's comment I have dropped the intridea Gem and am now using Signet. I get a little further but I am stuck getting an access_denied error when I specify a :person. Without that I can authenticate but obviously I get access as the issuer.
require 'google/api_client'
...
client = Google::APIClient.new(:application_name => application_name, :application_version => application_version)
...
opts = {
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => scope,
:issuer => service_account_email_address,
:signing_key => key,
:person => 'my.email#address.com'
})
client.authorization = Signet::OAuth2::Client.new(opts)
access_token = client.authorization.fetch_access_token!
...
>> client.authorization.fetch_access_token!
Signet::AuthorizationError: Authorization failed. Server message:
{
"error" : "access_denied",
"error_description" : "Requested client not authorized."
}
I have a console project which I do a 'test install flow' on but the client does not seem to be trusted. Where do I look?
Thanks.
Not sure how to do it with intridea's oauth2 gem, but the signet, the default for the ruby client library, handles this case directly.
There's a snip-it for how to do this in the readme. The only addition is, as you point out, adding the subject to get a token for the specific user. That can be specified either when instantiating the OAuth2 client or as an option to fetch_access_token!
Here's the summary.
Do not use the OAuth2 gem from intridea if you are only trying to authenticate with Google. Rely on the signet Gem.
If you use a service account, you can specify a :person element and it will work so you impersonate that user and work on their behalf.
When you test your integration you must do so against the domain in which your project is hosted. You cannot test in a third-party domain until you've published your app!