Understanding OAuth and client sessions - oauth

I'm learning about OAuth with the goal of allowing visitors to my website the ability to sign in with Twitter. I've been using the Python based oauth2 library as a learning tool, and I think I get most of it.
I understand that after the user authenticates with the service (Twitter in this case) the user is sent to the callback URL with the parameters oauth_token and oauth_verifier.
What I fail to understand is the proper way of storing this information in the users browser. How do I identify these values during subsequent requests? Am I required to create a session system as with a normal website, or is there some magic in OAuth that makes this unnecessary?

How you handle client sessions of people who visit your website is not covered by OAuth, that remains up to you (and the usual session management frameworks).
All OAuth does is tell you that the user really is the Twitter user he claims to be. You can then associate this piece of information with the user session on your site (just like you would if the login screen was on your own page).

there are two types of oauth_token and oauth_verifier in twitter API
first is request token that always come different on each process, that can be save into session using getRequestToken method
i m telling in PHP view , but logic are same in any language
/
* Get request token */
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
/* Save request token to session */
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
another is accesstoken: that is retrived via getAccessToken method
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
Array
(
[oauth_token] => 223961574-mEctH7SHai######
[oauth_token_secret] => G7Buyxn4okF31Ln3ulAh#####
[user_id] => 223961574
[screen_name] => ltweetl
)
these token are same which is in your registered application on twitter
and already given at below page...
http://dev.twitter.com/apps/{your_app_id}/my_token.

Related

Google oauth2Client.getToken is not returning id_token for other users

I'm implementing Google's 'code model' of Oauth2 and having trouble getting users' email - I wonder if this is a scopes problem or my misunderstanding about how to set up the code model. This sequence of events is already working:
Client loads https://accounts.google.com/gsi/client
Client starts call to google.accounts.oauth2.initCodeClient
Client gets code
Client passes code to one of my server endpoints
Server has an oauth2Client set up using the config with client_id, client_secret, and redirect URL = 'postmessage'
Server exchanges the code from the client for tokens
Server does oauth2Client.setCredentials(tokens) - this contains an access_token, which is enough for the client to make API calls to, e.g., retrieve the user's Google Calendar
Server is able to do oauth2Client.getTokenInfo(tokens.access_token);
There are various places along the way that involve scopes; I am probably getting something confused here. The client's initial call (step 2 above) uses
scope: 'https://www.googleapis.com/auth/calendar',
My code path on the server does define scopes anywhere.
In GCP, my project is set up with scopes
calendar.calendarlist.readonly, calendar.readonly and calendar.events.readonly
openid
/auth/userinfo.email
Here's the problem I'm encountering: when I go through this flow as a user and oauth with the account that owns the GCP project (this is a Google Workspace email, in case that matters), the tokens object that the server receives (step 6 above) has access_token, refresh_token and id_token - the id_token can be decoded to yield the user's email, and the user's email is also in the response to oauth2Client.getTokenInfo(token.access_token).
However, when I go through the flow with my other (personal) Gmail account, the tokens object that the server receives is missing the id_token but has the access and refresh tokens. Question 1: why are the responses different?
Question 2: How can I get the email of the user on the server in the personal Gmail account case? I've tried having the server make a call to https://www.googleapis.com/oauth2/v2/userinfo?fields=id,email,name,picture with the access_token, but this fails. I am not sure if I'm supposed to declare scopes for oauth2Client somehow, or tap a Google API using a different method on the server.
I think I've had a breakthrough: in step 2 in my original post, when I did "Client starts call to google.accounts.oauth2.initCodeClient", I had set the scope of initCodeClient to just the calendar scope. When I changed it instead to scope: 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email openid', (scope takes a space-delimited list in this case), it allowed my server call to get the id_token for this user and oauth2Client.getTokenInfo to get a response with the user's email in it.
When I updated the scopes like that, the popup asking for authorization also updated to request all the scopes I wanted - previously, it was only asking for the Calendar scope, so it makes sense Google didn't want to return the email.
What I still don't understand is why my previous setup was working for the account that owns the GCP project. In other words, when I was first building it out with that owner account, the client was only noting the Calendar scope while the server was asking for all three scopes (ie there was a mismatch), and the server was still able to get an id_token and the user's email in getTokenInfo. Maybe the owner account has some special privilege?

Session empty after redirect

I've a React JS app, which makes this request to my back-end API. i.e
window.location = "https://my-server.com" + "/gmail/add_account";
cannot set HTTP headers for window.location see this
this server endpoint redirects to Google OAuth page, which returns a response to my redirect_uri.
def add_account
# no auth headers sent here, because front-end has used window.location
gmail_service = GmailService.new
session[:uid] = params["uid"]
redirect_to gmail_service.generate_authorization_url()
end
def oauth_postback
# session object is {} here
# Since there are no authorization headers, I cannot identify my app's user
# How can I identify my app's user here?
end
The problem I'm facing is that when the OAuth flow sends the response to my redirect_uri it does not return include any authorization header, due to which I'm unable to identify which user of my app has launched this OAuth flow.
I've tried setting up a session variable in the /gmail/add_account endpoint, which works fine. After this endpoint redirects to the OAuth screen, and the Oauth flow sends a response to my Oauth redirect_uri, there my session object is {}.
How can I implement this flow such that I know which user has launched this OAuth flow?
You have basically two options:
the state parameter
The state parameter is part of the OAuth2 spec (and is supported by Google). It's a random string of characters that you add to the authorization URL (as a query parameter), and will be included when the user is redirected back to your site (as a query parameter). It's used for CSRF protection, and can also be used to identify a user. Be sure that if you use it, it's a one-time value (e.g. a random value that you store in your db, not the user's ID).
sessions with cookies
If the user has previously logged in, you should be able to identify them by their session cookie. It sounds like this is the approach you're currently taking, but the session is getting reset.
It's difficult to debug this without knowing more about your stack/code, but a good first step would be just trying to load your callback URL without the redirection to Google to see the session object is still empty. If so, that would indicate an issue with how you've implemented sessions generally and not something specific to this flow.
As a note, based on the code you've shared, I'm not sure how params["uid"] is getting set if you're doing a redirect without any query parameters or path parameters.
Finally, you may consider using a managed OAuth service for something like this, like Xkit, where I work. If you have a logged in user, you can use Xkit to connect to the user's Gmail account with one line of code, and retrieve their (always refreshed) access tokens anywhere else in your stack (backend, frontend, cloud functions) with one API call.

How to use Omniauth Asana with Rails API only app

I have a Rails 5 API only app and an Angular JS Frontend app and would like to integrate with Asana API. I'm using the ruby-asana, omniauth and omniauth-asana gems.
I start the request using Asana's JS library like so:
var client = Asana.Client.create({
clientId: 172706773623703,
clientSecret: '<client_secret>',
redirectUri: '<redirect_url>'
});
client.useOauth({
flowType: Asana.auth.PopFlow
});
And the above does redirect me to Asana where I can login. On the redirectUri I'm giving a backend route (Rails 5 API only) which should handle the remaining on the authentication (using the JS only I get only a temporary token that cannot be self renewed meaning the user will have to authenticate every time the token expires. This is if I understood the documentation correctly).
So, on the controller I've created to handle the route, I have the following (from an example on Asana's documentation):
require 'omniauth-asana'
use OmniAuth::Strategies::Asana, <secret>, <secret>
creds = request.env["omniauth.auth"]["credentials"].tap { |h| h.delete('expires') }
strategy = request.env["omniauth.strategy"]
access_token = OAuth2::AccessToken.from_hash(strategy.client, creds).refresh!
$client = Asana::Client.new do |c|
c.authentication :oauth2, access_token
end
Now, the above doesn't work because 1) there's no request.env as this is an API only app, so I've followed the instruction on Omniauth and have added the following to my config/application.rb:
config.session_store :cookie_store, key: '_interslice_session'
config.middleware.use ActionDispatch::Cookies # Required for all session management
config.middleware.use ActionDispatch::Session::CookieStore, config.session_options
Now, in the request.headers I have _interslice_session which has some numbers. How can I create a Asana client with the above?
Any ideas?
OK, I think I see what you're attempting to do here; I think the best way forward is to start with how OAuth's Authorization Code Grant happens in general, then move into specifics for OmniAuth.
You send the user to a URL that Asana owns; that is, your goal is to get the user to visit a particular url. For Asana, this is https://app.asana.com/-/oauth_authorize. (Note that we respond with an error if you don't sent a correct client_id param, but feel free to check that link if you want). Do not send the client_secret during this request - it is intended to never be involved in client-side code, as this is insecure.
If they agree to give access, Asana sends back a redirect request to the user's browser with a short-lived code. That then means that your server will be called from the user's browser with this code as a parameter, so has to handle a new incoming request from the browser to whatever you specified as your redirect URI. Also, this location must be accessible by all users of your integration wherever they are.
You send this code from your server as a POST request to https://app.asana.com/-/oauth_token with your client_secret to Asana for a refresh token. This is where your application actually asks for credentials; the token given in the previous phases simply acknowledges that for a short time, the user has given your app permission to ask for these credentials, and your client_secret assures Asana that, for this server-side request, your app really is yours (it's like your application's password).
We send back an access_token which represents (approximately) a client-user credential pair that is valid for an hour.
You use these credentials to access our API on behalf of this user. We also send back a refresh_token which is long-lived, and used to get new short-lived access_tokens after they expire in a very similar way.
OK, so how this works with OmniAuth if I grok it correctly is that it expects to handle almost all of it. I'll be working through our omniauth example in our ruby-asana client library here: https://github.com/Asana/ruby-asana/blob/master/examples/omniauth_integration.rb
You set up OmniAuth with your client id and client secret
use OmniAuth::Strategies::Asana, <client_id>, <client_secret>
A request comes in, and you don't have credentials for it.
get '/' do
if $client
...
else
'sign in to asana'
end
end
The user clicks the sign in link, which (code omitted) sends them to the sign_in endpoint. This endpoint issues a redirect to /auth/asana
The browser requests /auth/asana from our server. If you look at that example, it's not implemented in our code. That's because the /auth/:provider is magically handled by OmniAuth.
This is where all the magic happens. OmniAuth handles the entire login flow above: send browser to our oauth_authorize above, then receive the callback and sticks the relevant params in the environment such that it knows "we just got the short lived code". By the time these lines get hit:
creds = request.env["omniauth.auth"]["credentials"].tap { |h| h.delete('expires') }
strategy = request.env["omniauth.strategy"]
you are inside a callback that OmniAuth has intercepted, gotten the needed creds, and set the creds in the environment. You shouldn't have to handle the oauth callback and token exchange manually.
Now, with the code you provided, I notice a few things right off:
You are causing the popup cycle to happen client side. It may be (and I strongly suspect) that this won't work with OmniAuth - it expects to handle the whole OAuth flow.
Based on the code snippet you provided, you aren't serving this out of a request-response cycle in the controller, rather, it appears that this is in the controller body and not out of an instance method. It may be a typo, but this needs to be in a method that is called back to outside of Rails (that is, a route must point to this a controller method that Asana can use to handle the browser request).
You shouldn't have to look at request.headers, I think - I'm not sure what the issues might be with request.env, but I suspect they may be unrelated to the API-only nature of your app. Are you sure that this is because it's API-only? After adding in the middleware, did you double-check that you can't access request.env? My hunch would be that persistent data in request.env will still be there, only it would require on the middleware being added in to do this. The instructions on OmniAuth simply say that you need to have a session store for your API - which makes sense to me, because APIs don't necessarily need to store state across requests, OmniAuth is telling you to put a session store back in.
I know this is a lot of info, but hopefully it helps you get on the right track. Cheers!

Refresh token with Twitter API

I'm wondering if Twitter has an API endpoint that exchanges an expired access token with an active one. The way that I have the login flow working right now goes something like this.
// Request a token and redirect to the authorization page
$token = $this->twitter->getRequestToken();
// Set the session data
$this->session->set_userdata('oauth_token', $token['oauth_token']);
$this->session->set_userdata('oauth_token_secret', $token['oauth_token_secret']);
// Redirect the user to the authorization page
header('Location: https://api.twitter.com/oauth/authorize?oauth_token='.$token['oauth_token']);
The page that the user is redirected to will prompt the user to authorize my app each and every time they want a valid access token. Upon accepting the authorization, the user will be redirected to the callback URL. At my callback URL, the following happens
// Get the parameters from the URL
$token = $this->input->get('oauth_token');
$verifier = $this->input->get('oauth_verifier');
$oauthToken = $this->session->oauth_token;
$oauthSecret = $this->session->oauth_token_secret;
// Get the access token
$access = $this->twitter->getAccessToken($verifier, $oauthToken, $oauthSecret);
Does such a way exist for an access token to be generated without having to authorize my app each and every time?
According to Twitter's OAuth FAQ, tokens don't expire unless a user explicitly rejects your application or an admin suspends your application.
If you want your users to be able to login repeatedly without having to reauthorize, you'll need to come up with a mechanism for storing the tokens (cookies, database, etc.).

Myob - AccountRight Live Api v2 Skip login screen

I am using accountright Live api v2 by MYOB. I want to get access token without going to login screen. When I send a CURL request to obtain access token i am redirected to myob login screen, how to skip that? The request I am sending is to url:
'https://secure.myob.com/oauth2/v2/authorize'
and params sent are:
Array
(
[client_id] => xxxxxxxxxxxxxxxxxxxxxxxx
[client_secret] => xxxxxxxxxxxxxxxxxxxxx
[scope] => CompanyFile
[code] => XXXXXXXXXXXXXX
[redirect_uri] => http://myappcodeonmydomain.com
[grant_type] => authorization_code
)
After your initial request to the API to get the access token, you should also be provided with a refresh token. Access tokens expire after a period of time, and need to be refreshed.
From the Refreshing an Access Token section in the Authentication Documentation:
Access tokens have a limited life span and when you receive one you'll
also receive an Expiry Time for it and a Refresh Token. Once your
access token expires it can no longer be used to access the API. So
you'll need to trigger a refresh. You do this by POSTing the following
parameters:
'client_id' // your API Key
'client_secret' // your API Secret
'refresh_token' // your refresh token
'grant_type' // this should say refresh_token
To this url: https://secure.myob.com/oauth2/v1/authorize
Note: while the data is formatted into a URL Query String you do not
pass the information via the URL (that would be a GET request), you
must pass the query string in the body and POST this to
https://secure.myob.com/oauth2/v1/authorize
As an example, I store my access and refresh tokens in a database, along with an expected expiry time 10 minutes in the future. If a request is going to be made after that time, I call the refresh procedure to update the access token, and am able to proceed on my merry way without needing to show the login prompt each time.
You do need to have it shown at least once to find out which user is logging in, and the GUID of the Company File to connect to.
If you are talking about the first time auth, then there is no way to do it. You have to redirect the user to the login page by returning the url.
If you are talking about refresh the token, then it's easy.
I'm not sure how you implement the API connection. I'm using the myob ruby sdk.
The ruby sdk is so easy to use and it will do all those auth operations for you.
:)

Resources