Generate a token every day inside a service - java

I have to create an endpoint, which collects information and then it inserts to a BBDD. The problem is to access this information, the token must always be added to the query params and it expires every 20 hours.
To get the token, firstly I have to make it a call like this one
https://url/token.php?username=...&password=...
I'll get a response like this one
{"success":true,"token":"aaaa","expire":1589780649}
An example of the endpoint to gather information would be
https://url/information.php?token=aaaa&fields=a,b
I have to say that I am new to java spring (and java in general). Is there a way to create a microservice that, before collecting the information, obtains the token every 20 hours?

If you save token in DB, then you can check token on expiry after any request
For example:
if (token.getExpire > 20 hours) {
Token token = tokenRepository.findByToken(token);
if (token != null) {
generateNewToken();
remove and save new token or change old token in DB
}
}

Related

Is refresh token mandatory for TD Ameritrade API?

I'm trying to use this Java library for TD Ameritrade https://github.com/studerw/td-ameritrade-client
Here is the starting code
Properties props = new Properties();
props.setProperty("tda.client_id", "XXX#AMER.OAUTHAP"); // I have this
props.setProperty("tda.token.refresh", "XXX"); // I don't have this
I have a client_id, a.k.a. consumer key
But I don't have a refresh token. I only want to use the Quotes API, I don't want to make any actual trades. I'm able to test the consumer key here https://developer.tdameritrade.com/quotes/apis/get/marketdata/quotes and it works great. Do I have to obtain refresh token too? Is it mandatory? Is there any way to use consumer key only without the refresh token?
Here https://developer.tdameritrade.com/quotes/apis/get/marketdata/quotes it says "Authorization Token aka Refresh token is Optional", so is it really "Optional"
As far as I can tell, if you have tokens, you will get more up to date quotes. If you do not, you will get delayed data:
Pass your OAuth User ID to make an unauthenticated request for
delayed data.
If you want more realtime data (I do not have an Ameritrade account, not sure exactly what the delay difference is), you can use tokens:
(Optional) The Authorization token to validate the request. Not
required for un-authenticated requests
(Un-authenticated requests being the above delayed route)
Alternatively, if you want a Refresh Token, which expires every 90 days and is used to gain an Access Token (expires every 30 minutes), the steps are listed here:
https://developer.tdameritrade.com/content/simple-auth-local-apps
That will give you a refresh token that you can use for 90 days to
request access tokens and allow you to authenticate without needing a
server. Note that you will need to update your app's refresh token at
least once every 90 days to keep it functioning.
Again, I do not have a TD Ameritrade account to personally confirm this, but looks like you have at least two options to get Quotes.
Further FAQ resources:
https://developer.tdameritrade.com/content/authentication-faq

How to get an access token using a refresh token in Java?

I am currently implementing Contact Application using Google Contact API in Java. I have completed steps of authorization and obtained an access token and a refresh token.
Now I have the CLIENT_ID , CLIENT_SECRET AND REFRESH_TOKEN with me . But the access token is getting expired within an hour.
Can someone tell how to automatically generate an access token using a refresh token in Java?
You can use Google OAuth2 client library for getting a new access token using a refresh token.
Here is my code for getting a new access token:
public TokenResponse refreshAccessToken(String refreshToken) throws IOException {
TokenResponse response = new GoogleRefreshTokenRequest(
new NetHttpTransport(),
new JacksonFactory(),
refreshToken,
"your clientId",
"your clientSecret")
.execute();
System.out.println("Access token: " + response.getAccessToken());
return response;
}
For more information read the official Google API guide:
OAuth 2.0 and the Google OAuth Client Library for Java
I have implemented this scenario in two ways. Not sure they are the best or not but works well for me.
In both cases you have to store the refresh token along with the email id of the user. Then you have to make a HTTP request in the below format.
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
client_id=**<your_client_id>**&
client_secret=**<your_client_secret>**&
refresh_token=**<refresh_token>**&
grant_type=refresh_token
It will return the access_token and expires_in
Source
Now the question is how and when to do the http request. So for that I have two ways.
1st one
Store the emailid,refresh token, access token and the current time+3600 seconds. In your database you can schedule to check the expire time in every 5 min and if current time of any user is going to reach(before 5 or 10 min) the expire time, get the refresh token and update the value for that particular user. And during api call just fetch the access token of the user.
2nd one
When user do login in your site, get the access token and current time+ 3600secs and store it in browser cookies. Now before doing any api call just check whether the current time(time when api call is done) is less than the expire time(stored in cookie). If its true then you can use the previous access token else get a new one and again update the cookie. Also you have to put another condition that if the cookie is not present at all then also you have to get new refresh token.

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 can I reset the JWT token expiration time?

I have created a JWT token along with expiration time for authentication purpose.
Each time
when a url hits in the application i am checking for the token. I want to increase the JWT token expiration time. The following is how i done. but the token is expiring by taking the expiration time which is already set while creating the token.
//creating JWT token only once when user logged in
String jwtToken = new String(Jwts.builder().setSubject(user.getUserId())
.setExpiration(expTime).setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, "secretkey").compact());
// checking the presence of token every time
Claims claims = Jwts.parser().setSigningKey("secretkey")
.parseClaimsJws(jwtToken).getBody();
claims.setExpiration(time); // trying to reset the expiration time
I don't know what's going wrong. Any help would be much appreciated.
I think the expiration time is part of the token itself and it's not possible to extend the expiration time of a token without a new one.
Please refer to JWT (JSON Web Token) automatic prolongation of expiration for more discussion about this.
You'll need to recreate the token. All the information in the token is signed, making the token unique depending on the values in the token. Changing the claim that you pull from the token doesn't do anything.
It seems expTime defined in the previous code lines.
ex:- You can change this value.
int expTime = 43200000 //after 12 hours(Should in ms)
I think the best practice is to set this in the property file as follows. Then you can change that time after building the project.
app.expTime=43200000
After that call this value from token provide file
#Value("${app.expTime}")
private int expTime;

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

Categories

Resources