How to get access token using refresh token? - java

In my app we want to provide login with google. So i went throught the folowing Quickstart and created a sample extending it by setting access_type to offline. So that i can get refresh token as their will be background task that will perform operation on those account after a particular interval of time, example: saving starrred mail in some file on server for each user.
So i need to know:
How to save refresh token ? like save it in DB with userId or somthing or save whole credential object as few post i have seen use credential object
How to use refresh token to get accesstoken ?
When does refresh token expires?
Code reference will be very useful.
Thank you!!

1.You can save the refresh token in DB as like userId, you can get new access token by using the refresh token
2.You need to pass the Client Id, Client Secret and Refresh token to get the new access token
3.Refresh tokens are valid until the user revokes access.

Related

Create refresh and access token jwt using java

I am using jjwt to create token using the documentation on github https://github.com/jwtk/jjwt#specification-compliant
I understood that I have to create a refresh token store it on my database and use it to create an access token for the user. But I don't find a simple example to help me to understand how to code it. I am able to create a token following the github documentation but i don"t know how to create a refresh token and then an access token using my refresh one.
I am using java on android studio and as back up api using App Engine Java servlet module
even that it has been a long time since then:
You have 2 tokens: one that expires fast (token) and one that expires after a very LONG TIME (refresh token).
The reason for this is because refresh token is actually used very rarely and you don't send it over the network so often. if you send a token very often over the network you have to make it expire fast (it's up to you to decide how long a token lives 30 mins/1 hour/2 days).
When the JWT token where you store the data has expired you use the refresh token (from client side which should be stored securely) and get another token that you send very often over the network.
The flow should be like this:
login with credentials => get token (2hours expiry) and refresh token(30 years expiry);
client stores both tokens securely
token expired
using refresh token make a request and get another token that expires in 2 hours
refresh token expires after 30 years - logout the user
The refresh token is just used to not put the user insert credentials again
Well, it has been a long time, but I think neither of already posted answers actually addresses the original question. Let me handle it:
You should understand, that, technically speaking, your Refresh Token could be anything. Let me explain: you need Refresh Token just to later on reissue an Access and Refresh tokens pair. In most cases, you should store your Refresh Token in database (or in-memory Cache, like Redis). Technically you do not obligated to sign a Refresh Token, or encrypt it. Do the following:
Generate Access Token (and of course, it must be signed)
Generate Refresh Token the way you want. It can be almost the same JWT, but with far more extended TTL (Time to live). Store it in some data storage, again depends on your requirements
Once the Access Token get expired, the Client, to which you have issued tokens, come to you with the Refresh Token you have generated on the step 2. You will pull Refresh Token you have saved on the previous step, check for their equality. If everything is alright (Refresh Tokens matches) - repeat procedure from the first step. That is it.
Hope it helped
Creating a refresh token is just creating a "normal" token with new (refreshed) data (claims) in it.
It only makes sense if your claims that the server issues change over the time like e.g. the expiration time. Obviously only the token issuer (I assume the server in your case) can refresh the tokens and client needs to poll for them or the server needs to notify the client.
On the server just create the new token with a future expiry time filled in:
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(new Date());
cal.add(Calendar.HOUR_OF_DAY, 1);
cal.getTime();
String compactJws = Jwts.builder()
.setSubject("Joe")
.setExpiration(cal.getTime();) // set expiration to e.g. one hour in the future
.signWith(SignatureAlgorithm.HS512, key)
.compact();
Hint: you cannot invalidate JWT tokens apart from putting them on a central blacklist what kind of cannibalizes the concept of JWT.

How to auto-authenticate with box.com java sdk

My question is similar to this post:
How to get an access token without Box’s authorization page
In that post, he asks:
I have been granted access(collaborate) in a folder. What I need is to access the folder daily and fetch files from it. Right now the developer token I generate expires in 1 hour. Is there a way I can get the authorization code without the first leg, which requires a user interface. This way I can refresh the access toke whenever I fetch files.
The highest rated answer from "Skippy Ta" tells me most of what I need to know EXCEPT the following:
How do I authenticate using the developer token and how do I refresh? From the github repo for the HelloWorld sample app (https://github.com/box/box-java-sdk-v2) I downloaded, I see these two steps:
boxClient.authenticate(boxOAuthToken);
for the initial authentication, and
boxClient.addOAuthRefreshListener(new OAuthRefreshListener() {
#Override
public void onRefresh(IAuthData newAuthData) {
// TODO: Update the stored access token.
}
});
for the refresh.
I'm having trouble putting all this together. First, the authenticate method does not accept a String boxOAuthToken, it accepts an IAuthData object, whatever that is. So I cannot conduct the initial authentication.
Even if I were to achieve initial authentication, I could not refresh, because I don't know how to access the token once I'm authenticated in order to store it, and if I stored that token as a String, I don't know how to wrap it in the proper object and conduct the update alluded to by the
// TODO: Update the stored access token.
comment above. Thanks for any help you can offer.
You can take a look at the javafx login UI: https://github.com/box/box-java-sdk-v2/tree/master/BoxJavaFxOAuth
But anyway if you need to build a BoxOAuthToken object from access token and refresh token and authenticate from it, here is what you can do:
HashMap<String, String> tokenMap = new HashMap<String, String>();
tokenMap.put("access_token", access);
tokenMap.put("refresh_token", refresh);
BoxOAuthToken token = new BoxOAuthToken(tokenMap);
boxClient.authenticate(token);
As for the refresh, the sdk auto-refreshes. The only time you need to worry about it is when your app quits and you need to persist the auth. At that point you can save the oauth token out. The refresh listener is used to update the oauth token for you so at the point you need to save oauth out, you have the latest oauth data.

Why Facebook Access Token Changed Each and Every Access?

We are using restFB 1.6.12. I am getting the facebook access token in two ways,
1. CLIENT_APP_ID = "XXXXXXXXXXXXXXXXXX";
CLIENT_SECRET = "XXXXXXXXXXXXXXXXXX";
REDIRECT_URL = "XXXXXXXXXXXXXXXXXX";
AUTH_CODE = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
SCOPE = "email,read_stream";
Redirect to facebook as the example. As a result I'll get an
authorization code
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream
asking for an access_token using,
https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE
this returns the access token like this,
access_token=CAAHWfjdHDKcBAIL0zHMeJKzJw8Ug7WrrrkNxpBnK7ubnFR1RGtIIZA7T3UPlhCSV0hPJXZAgTcKfBSfHZAyxsndc3RT72XMREjACxnGb0ZCGMZAUgDWH3FgOhnaoSBMgkaQBPDOCCEKcLnznMYSncWS7dVxl9IFrSzeFjF6LKOWB3NTynl5X1&expires=5125218
2. AccessToken accessToken = new
DefaultFacebookClient().obtainAppAccessToken(appid,appsecret);
String token=accessToken.getAccessToken();
It reurns the access token like this,
access_token=517312558337191|5oHY9T3cZICO_TCeK8OdXKg5Y08
If I use the first(1) one, it works fine for first access after then every access throws an error
Auth Token= {"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100}}
If I use the second(2) one, it works fine only for publicSearchMessages but when I access publicEvents or other searches it throws an error
com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: (#200) Must have a valid access_token to access this endpoint
at com.restfb.DefaultFacebookClient$DefaultGraphFacebookExceptionMapper.exceptionForTypeAndMessage(DefaultFacebookClient.java:766)
at com.restfb.DefaultFacebookClient.throwFacebookResponseStatusExceptionIfNecessary(DefaultFacebookClient.java:688)
at com.restfb.DefaultFacebookClient.makeRequestAndProcessResponse(DefaultFacebookClient.java:630)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.java:592)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.java:556)
at com.restfb.DefaultFacebookClient.fetchConnection(DefaultFacebookClient.java:219)
My question is, what is the difference between these two access token and how can I programmatically generate access code for first one to works publicSearchMessages, getPublicEvents and other searches?
Which one access token is used to works as expected?
Access_tokens allow users to interact with your apps in secure and social ways. While we are removing the use of the offline_access permission, through a migration setting in the App Dashboard, we are now allowing the option to use access_tokens with a long-lived expiration time that can be renewed each time the user revisits your app
When a user visits your site with an existing, valid, short-lived user access_token, you have the option to extend the expiration time of that access token.
extend the expiration time once per day, so even if a user revisits your site multiple times a day, the token will be extended the first time requested. You must make sure to call the new endpoint below before the short-lived access_token expires.
Using the new endpoint below, you will be able to extend the expiration time of an existing, non-expired, short-lived user access_token.
To get the long-lived user access_token simply pass your own client_id (your app_id), your app_secret, and the non-expired, short-lived access_token to the endpoint. You will be returned a new long-lived user access_token; this access_token will exist in addition to the short-lived access_token that was passed into the endpoint
In short Get a page access token – those don’t expire per default; and make sure to do so with a long-time user access token
You can access facebook doc here for more info
To get an extended Page Access Token, exchange the User Access Token for a long-lived one and then request the Page token. This "extended" token for Pages will actually not have any expiry time.
https://developers.facebook.com/docs/howtos/login/extending-tokens/#step1
resolve this by executing a curl request, and saving "Page access token" in your code manually

What is the expiry time of the code parameter returned by google?

I am integrating google calendar api, I have a url that is the redirect url after the application access is authenticated, the url returns a parameter code like
redirectUrl/code?='somecode'
i want to know the time expiry for the parameter code
The default is 3600 seconds, or an hour. But if you make requests after that, the previous code will be invalid, but I'm sure you know that.
https://developers.google.com/accounts/docs/OAuth2UserAgent#handlingtheresponse
The expiry of the access token is 3600 seconds only.
it could be revoked using refresh token or the access token it self, you may use the refresh token if the approval prompt for the google approval is kept "auto", but in the case you would get refresh token only once, using refresh token the response does not returns refresh token in this case but if you will use access token refresh token shall be generated with it, but if you use approval prompt of "force" type then you shall get the approval window every time.

Android Facebook SDK Invalid access token after authorization

I'm trying to get friend list of users in my Android app. To do so I'm using:facebook-android-sdk-3.0.1.
The SDK comes with it's own loging/logout button so I used it. When I click login it handles the event(calls login screen asks for permission) so I have nothing to do. Right after login, onSessionStateChange function being called which is inside the A_class extends Fragment
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) { // Session open
getFriends(); // Call FQL codes...
} else if (state.isClosed()) { // Session closed
// After first login, It always coming here.Couse:Invalid access token.
}
}
I've followed the tutorials. I was able to: login > ask basic permissions > fetch the friend list(by using FQL) > logout.
After the first successfull login and authentication, If I Logout/Exit from the app, I'm not able to login again. In SDK's finishAuthorization it returns Invalid access token exception, which fails the session to open.
If I login my facebook account on browser and deauthorize the facebook application on my account, I'm able to login again and fetch friends. It looks like I have to refresh the access token or something... Thank you for any suggestions.
I've figguredout that the token is returning empty string "".
Do you try to re-authorize after logout ? Maybe the token expires. In my apps, I dont do a logout. The token is valid, till it expires. So in that case I login again :).
I can't say what the fix is to your exact issue but I remember having a similar problem with FB where the token existed but was invalid.
Basically what happens in the sdk, if I remember correctly, is this
FB auth -> have token? -> yes -> create session with token
As you can see in the above there is no step to check if the token is valid so it's always returning a session that has been closed.
You should try to forcefully flush the token from memory on logout thus avoiding the FB sdk giving you a Session with an invalid token.
The above is just a guess so take it with a pinch of salt.
First check the availability of your access token from Facebook debug tool from Here https://developers.facebook.com/tools/debug/access_token. This tool will provide you with some info about the access token provided like Time to Expire and Scopes ... etc
If the token is expired you have to refresh it (re-authorize it) using the graph api:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=app-id&client_secret=app-secret&fb_exchange_token=old_token
Just replace old_token in the URL with the expired access token and use your app_id and secret instead of client_id and client_secret respectively. The return value is a new token that you can use instead of the old one.
You can refresh the access token at the time you got the exception of invalid access token and replace it before logging in.

Categories

Resources