Mule OAuth Provider Accesstoken expiry time - oauth

I am using Mule enterprise edition and struggling to find the default expiry time for tokens issued using the Mule OAuth provider. So if my provider configuration is like the below, for how long will the issued access token be valid ? 12 hours/24 hours or something else ?
<oauth2-provider:config name="oauth2-provider"
providerName="E2 Provider" resourceOwnerSecurityProvider-ref="boston-security-provider"
scopes="READ WRITE" supportedGrantTypes="RESOURCE_OWNER_PASSWORD_CREDENTIALS"
doc:name="OAuth provider module" port="${auth.port}" enableRefreshToken="true">
<oauth2-provider:clients>
<oauth2-provider:client clientId="${web_client_id}"
secret="${web_client_secret}" type="CONFIDENTIAL" clientName="Web Client"
description="Mobile Client desc">
<oauth2-provider:authorized-grant-types>
<oauth2-provider:authorized-grant-type>PASSWORD</oauth2-provider:authorized-grant-type>
<oauth2-provider:authorized-grant-type>REFRESH_TOKEN</oauth2-provider:authorized-grant-type>
</oauth2-provider:authorized-grant-types>
<oauth2-provider:scopes>
<oauth2-provider:scope>READ</oauth2-provider:scope>
<oauth2-provider:scope>WRITE</oauth2-provider:scope>
</oauth2-provider:scopes>
</oauth2-provider:client>
</oauth2-provider:clients>
</oauth2-provider:config>

I have found the answer it is 86400 seconds which is 24 hours. Link to the documentation is here, however the description for Token Ttl Seconds is misleading, It should be seconds instead of milliseconds. I have logged a jira for the same here

Related

How to get a forever token using Oauth1?

I sell products online through a website I wrote. To manage my fulfilment flow, when a purchase is made I want my app to automatically create a card on a Trello board.
I've managed to do everything okay except that after a few minutes the token that I was using expires, even though I thought I had created a token that would never expire.
I can't manually authenticate every time an order comes in.
Here's the code I've written to generate tokens. (Oauth1).
Step 1 (one time): Get a manually authorized resource owner key, resource owner secret, and verifier.
import requests
from requests_oauthlib import OAuth1Session
oauth = OAuth1Session(CLIENT_KEY, client_secret=CLIENT_SECRET)
fetch_response = oauth.fetch_request_token(REQUEST_TOKEN_URL)
resource_owner_key = fetch_response.get('oauth_token')
resource_owner_secret = fetch_response.get('oauth_token_secret')
print(f'resource_owner_key: {resource_owner_key}')
print(f'resource_owner_secret: {resource_owner_secret}')
auth_url = oauth.authorization_url(AUTHORIZE_TOKEN_URL, scope='read,write', expiration='never') # expiration never
print(auth_url)
# Now manually authenticate in browser using this URL. Record resource owner key, secret and verifier
Step 2 (every time): Use resource owner key, resource owner secret, and verifier to generate a token.
oauth = OAuth1Session(CLIENT_KEY,
client_secret=CLIENT_SECRET,
resource_owner_key=RESOURCE_OWNER_KEY,
resource_owner_secret=RESOURCE_OWNER_SECRET,
verifier=VERIFIER)
oauth_tokens = oauth.fetch_access_token(ACCESS_TOKEN_URL)
token = oauth_tokens.get('oauth_token')
Step 3: Use token in POST request to make card.
This all works fine for a few minutes, then on trying to use it again I get the error:
requests_oauthlib.oauth1_session.TokenRequestDenied: Token request failed with code 500, response was 'token not found'.
I thought that token was last forever? I can still see under my account details on Trello:
read and write access on all your boards
read and write access on all your teams
Approved: today at 6:30 AM
Never Expires
Set expiration long expiration time in token like expire in 2099 something like that
Solved - I was doing everything right, just that Step 2 should only be done once instead of every time. I thought I had to generate a new token for each new request, but the token generated at the 'token = ' line is actually good to save off and use forever.

Youtube oAuth promts authorization window every time I make request

Here is my work flow for getting access token and refresh token for youtube api. Im generating authorization url with parameters
access_type=offline, response_type=code, redirect_uri=uri, scope=scopes, state=state, client_id=id
from authorization url I´m receiving authentication code, then I´m generating another url to get access_token and refresh_token using code from authorization url with these parameters
code: code, client_id: CLIENT_ID, client_secret: CLIENT_SECRET, redirect_uri: serviceCallback, state: state.callback, grant_type: "authorization_code"
As far as I know user should complete this process only once and then it should be automatic. My problem is that I´m always have to complete authorization and I´m getting always new access_token and refresh_token without forcing it on request.
here is code part where I´m getting authentication url
getAuthUrl: function(scopes, applicationCallback, serviceCallback, siteId,
selectChannel, websiteUrl) {
var requestedClientId = CLIENT_ID;
var scopess =
"https://www.googleapis.com/auth/yt-analytics.readonly https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/userinfo.email " +
scopes.replace(",", " ");
return "https://accounts.google.com/o/oauth2/auth?" +
"access_type=offline" +
"&response_type=code" +
/*"&approval_prompt=auto" +*/
"&redirect_uri=" + serviceCallback +
"&scope=" + scopes +
"&state=" + JSON.stringify({
service: NAME,
callback: applicationCallback,
scopes: scopes,
siteId: siteId,
selectChannel: selectChannel,
websiteUrl: websiteUrl
}) +
"&client_id=" + requestedClientId;
},
From there Im getting back code and using that code, clientID and clientSecret to get access token and refresh token
getAuthTokens: function(code, state, res, serviceCallback) {
// Google oAuth endpoint
var endpoint = "https://www.googleapis.com/oauth2/v4/token";
const scopes = state.scopes.split(" ");
// Setup request data
var data = {
code: code,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
redirect_uri: serviceCallback,
state: state.callback,
grant_type: "authorization_code"
};
request.post(endpoint).send(data).type('form').set('Accept',
'application/json').end(function(err, oAuthResponse) {});
},
I was using wrong endpoint url I changed it to different one to one provided by youtube api documentation and removed state parameter from data variable but still doesnt fix the problem
new endpoint url
var endpoint = "https://accounts.google.com/o/oauth2/token";
I´m really confused right now because I´m not forcing authorization and on google apps section there is my app already authorized and it does not update authorization that means it gives permission only first time and after that when I´m pressing allow it doesn´t do anything. OAuth should check if I have refresh token or not, so my conclusion is that I don´t fully understand how it should work or I´m somehow testing everything on debug or test mode where authorization prompt is automatically forced.
I would be really thankful for any kind of help because I feel like I tried everything.
The issue is that the access token that you are using has expired before the next time you use as you have not updated the access token manually using the refresh token.
You need to use the refresh token to update the access token if [ (time you last updated the access token) + (the expiry time) ] has already surpassed.
The concept of refresh tokens is that if an access token is compromised, as it is short-lived, the attacker has a limited time period in which it can be used. Refresh tokens, if compromised, are useless because the attacker requires the client id and client secret in addition to the refresh token in order to gain an access token.
The YouTube API documentation demonstrates the procedure here
By default, the expiry time is around 3 seconds.
This will surely, work in your case.
Adding the following parameter to your authentication object may help...depending on your requirements:
prompt: 'none'
This would mean no consent is gained or needed, after an initial authorization to use the app.
Go to the my accounts settings of google for this account---> go to connected apps and sites ----> manage apps:
Over there can you see the permissions for youtube like this:

How can I refresh a google plus bearer token (javascript)?

I'm using the google HTML sign-in button in my single page (javascript) application to obtain an authorization object from users with Google logins. This is detailed here: https://developers.google.com/+/web/signin/add-button.
I successfully receive back a token such as shown below. Since this token expires in 1 hour, I need to refresh the token every 30 minutes or so, until the user choses to log out. I am attempting this by calling:
gapi.auth.authorize({client_id: "90... ...92.apps.googleusercontent.com", scope: "profile email", immediate: true}, function() { console.log( arguments ); } );
but with no luck. I receive the same token back until it expires, after which I get back the empty (not signed in) token. How can I preserve / refresh the bearer token without the user having to continually log in again?
{
_aa: "1"
access_token: "ya29.1.AA... ...BByHpg"
authuser: "0"
client_id: "90... ...92.apps.googleusercontent.com"
code: "4/Nyj-4sVVcekiDnIgMFh14U7-QdRm.svPMQSODiXMbYKs_1NgQtmX9F90miwI"
cookie_policy: "single_host_origin",
expires_at: "1398341363",
expires_in: "3600",
g_user_cookie_policy: undefined,
id_token: "eyJhbGciOiJ... ...0Es1LI"
issued_at: "1398337763",
num_sessions: "2",
prompt: "none",
response_type: "code token id_token gsession",
scope: "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
session_state: "b92d67080... ...73ae",
state: "",
status: {
google_logged_in: true,
method: "AUTO",
signed_in: true
},
token_type: "Bearer"
}
Using the client side flow (ie Java Script) you can only receive short-lived (~1 hour) access_token. If you want to be able to refresh it, you need a refresh_token which can only be obtained using the server side flow.
You can find more information here.
Basically,it works like this :
The user connects to your Website and clicks on the "Sign-in button"
You receive an access_token and a code in JavaScript
You send this code to a PHP Script on your web server
The script makes a request to Google Servers and exchanges your code for an
access_token(which should be identical to the one you just received in JavaScript) and a refresh_token
You need to store this refresh_token somewhere (in a data base for
example) because it will only be issued once (when the users grants
permission)
When one of your access_token is about to expire, you can use your
refresh_token to get another valid access_token
As well as setting a timer, you should check that your token is still valid before making the API call. Now that the client library returns promises, and promises are chainable, you can do it really elegantly.
See my gist here.

CXF 2 legged oauth example

is there an example of a 2 legged oauth implementation with cxf ?
the documentation has an implementation for a 3 legged implementation, but not a 2 leg.
thanks
For 2 legged implementation you need to use either "password" or "client_credentials" grant.
The first one is for acting on behalf of an end user, and the second one is for acting as a client app itself.
There is an example in their docs right now. Let me know if it doesn't work for you.
Here's the code that I ended up using.
WebClient client = WebClient.create(LOGIN_ENDPOINT);
Consumer consumer = new Consumer(CLIENT_ID, CLIENT_SECRET); //The registered client
ClientAccessToken accessToken = OAuthClientUtils.getAccessToken(client, consumer, new ResourceOwnerGrant(USER_ID, USER_SECRET), false);
It implements the "Resource Ownner Password Credentials Access Grant Type"

How to use OAuth access for GMail with libEtPan?

Does anyone have sample code or clear instructions on how to use libEtPan to connect to a GMail account using OAuth? I couldn't find anything.
Details for OAuth in GMail are here: http://code.google.com/apis/gmail/oauth/
libetpan has some documentation in its header files, for IMAP it's in https://github.com/dinhviethoa/libetpan/blob/master/src/low-level/imap/mailimap_oauth2.h
/*
mailimap_oauth2_authenticate()
Authenticates the client using using an oauth2 token.
To gather a deeper understanding of the OAuth2 aunthentication
process refer to: https://developers.google.com/gmail/xoauth2_protocol
For a quick start you may follow this brief set of steps:
1. Set up a profile for your app in the Google
API Console: https://code.google.com/apis/console
2. With your recently obtained client_id and secret
load the following URL (everything goes ina single line):
https://accounts.google.com/o/oauth2/auth?client_id=[YOUR_CLIENT_ID]&
redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&
response_type=code&scope=https%3A%2F%2Fmail.google.com%2F%20email&
&access_type=offline
3. The user most follow instructions to authorize application access
to Gmail.
4. After the user hits the "Accept" button it will be redirected to another
page where the access token will be issued.
5. Now from the app we need and authorization token, to get one we issue a POST request
the following URL: https://accounts.google.com/o/oauth2/token using these parameters:
client_id: This is the client id we got from step 1
client_secret: Client secret as we got it from step 1
code: This is the code we received in step 4
redirect_uri: This is a redirect URI where the access token will be sent, for non
web applications this is usually urn:ietf:wg:oauth:2.0:oob (as we got from step 1)
grant_type: Always use the authorization_code parameter to retrieve an access and refresh tokens
6. After step 5 completes we receive a JSON object similar to:
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"refresh_token":"1/fFAGRNJrufoiWEGIWEFJFJF",
"expires_in":3920,
"token_type":"Bearer"
}
The above output gives us the access_token, now we need to also retrieve the user's e-mail,
to do that we need to perform an HTTP GET request to Google's UserInfo API using this URL:
https://www.googleapis.com/oauth2/v1/userinfo?access_token=[YOUR_ACCESS_TOKEN]
this will return the following JSON output:
{
"id": "00000000000002222220000000",
"email": "email#example.com",
"verified_email": true
}
#param session IMAP session
#param auth_user Authentication user (tipically an e-mail address, depends on server)
#param access_token OAuth2 access token
#return the return code is one of MAILIMAP_ERROR_XXX or
MAILIMAP_NO_ERROR codes
*/
LIBETPAN_EXPORT
int mailimap_oauth2_authenticate(mailimap * session, const char * auth_user,
const char * access_token);
LIBETPAN_EXPORT
int mailimap_has_xoauth2(mailimap * session);
I haven't tried it out myself yet, but when I get around to implement it I'll post a link of the implementation.
Update March 2021
I finally got around to implement support for Google OAuth 2.0 in my email client nmail now. The commit can be viewed here but essentially I ended up doing steps 2-6 above in a separate external script, as libetpan does not do the token generation/refresh for us. The token handling is fairly straight-forward - see oauth2nmail.py for example.

Resources