Is refresh token mandatory for TD Ameritrade API? - java

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

Related

Get access token using Spring Security with a specific use-case

Is this use-case supported for Spring Security 5, or something else, where we don't have to reinvent the wheel? Thoughts on how to (re)implement this better?
Details are as follows. 3rd party vendor supplied endpoints. We pull info from upstream source then forward to the downstream vendor. Only 2 APIs are required:
Request Access Token
Save Info
Both are actually being called via a gateway. We've been given specifics:
(A)
The token request requires Basic Auth (standard header - usual base64 encoded). Gateway User and Gateway Password are provided.
Credentials for request token are provided to us:
Grant Type = password
Consumer Id
Consumer Secret
Account User
Account Password
It responds with an access token and few other details we don't really care about and of zero value to our use-case.
There is no expires_in info in the response. But I've tested it multiple times to know it does expire. Not sure how long right now, I could do more tests to determine that.
(B)
The save request requires a different custom header for the same Gateway User / Password, then a Bearer Authorization header in the call to the Save Info API.
Right now, all implementations for above are using RestTemplate. Working fine already. But a token is requested for each save which is costly. Before writing any caching, or some other logic to wait XY minutes before another token request is made, I would appreciate any other options which may already be possibly handled via Spring-specific libraries or further advise on how to handle this scenario.
Apologies if this is not the right place to ask this, or it has already been asked before. Been searching for a similar use-case but can't seem to find one.
Thanks.
Try any one of the option
You can use OAuth2ClientContext which stores your access token.
final OAuth2RestTemplate restTemplate=new OAuth2RestTemplate(resourceDetails, clientContext);
You can create session & store your token & user details inside it.
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, null,null);
SecurityContextHolder.getContext().setAuthentication(authToken);
from option 1 Or option 2 you can then fetch existing token for each request at your Filter e.g. PRE_AUTH_FILTER
Then check if token expired - if yes request new token Or call refresh token
Check Oauth2 expires_in in below :-
https://www.rfc-editor.org/rfc/rfc6749?

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.

Android, AccountManager and OAuth

I'm sure this is basic and I'm missing something. I've read through other answers on SO, I've googled, I've read resources and I just can't wrap my head around what I need to do.
I'm trying to figure out how to write an app that connects to Twitch's API, specifically how to authenticate with Twitch's api. Their documentation is here: https://github.com/justintv/Twitch-API/blob/master/authentication.md
I've created an app and stored my keys.
Now comes the part where I want my user to click a button which launches the authentication on their website. From what I can tell I do this by using an AccountManager. Except... I can't figure out what I'm supposed to do.
Here's the excerpt I've found online:
AccountManager am = AccountManager.get(this);
Bundle options = new Bundle();
am.getAuthToken(
myAccount_, // Account retrieved using getAccountsByType()
"Manage your tasks", // Auth scope
options, // Authenticator-specific options
this, // Your activity
new OnTokenAcquired(), // Callback called when a token is successfully acquired
new Handler(new OnError())); // Callback called if an error occurs
According to twitch's documentation I want to send the user to:
https://api.twitch.tv/kraken/oauth2/authorize
?response_type=code
&client_id=[your client ID]
&redirect_uri=[your registered redirect URI]
&scope=[space separated list of scopes]
&state=[your provided unique token]
And I simply have no idea how these two things need to be combined.
Firstly, I recommend to read the OAuth2 RFC. This should cover everything you need to know.
The AccountManager code snippet won't help you much unless there already is an app that provides authentication for Twitch. If that's not the case you either need to use an existing OAuth2 library or implement your own.
You could write your own AccountAuthenticator but that's a different challenge (and you still need some kind of OAuth2 client).
Doing it yourself is not that hard, see below.
Steps to implement it yourself
Twitch recommends to use the "Implicit Grant Flow" for mobile apps. That's what I'm going to describe below.
1. Get a client ID
Register your app as outlined in Developer Setup to get a client ID
As redirect URI you can use something like https://localhost:12398/, the actual port doesn't really matter.
2. Build the authentication URL
In your client app you need to construct the authentication URL like so:
https://api.twitch.tv/kraken/oauth2/authorize?
response_type=token&
client_id=[your client ID]&
redirect_uri=[your registered redirect URI]&
scope=[space separated list of scopes]
Apparently [your client ID] should be replaced by the client ID you've received from Twitch, same goes for [your registered redirect URI] (that's the URL above, i.e. https://localhost:12398/). [space separated list of scopes] is the list of scopes (i.e. features your want to access), see Scopes. Make sure you URL-encode the parameter values properly.
Assuming your client ID is 123456 and the scopes you need are user_read and channel_read your URL would look like this:
https://api.twitch.tv/kraken/oauth2/authorize?
response_type=token&
client_id=123456&
redirect_uri=https%3A%2F%2Flocalhost%3A12398%2F&
scope=user_read%20channel_read
Note that you should also pass a state parameter, just use a randomly generated value. You can also append the (non-standard) force_verify parameter to make sure the user actually needs to log in each time (instead of continuing a previous session), but I think you can achieve the same by clearing the cookie store (given that you open the URL in a webview in the context of your app) before you open the login page.
With a random state the URL would look like this:
https://api.twitch.tv/kraken/oauth2/authorize?
response_type=token&
client_id=123456&
redirect_uri=https%3A%2F%2Flocalhost%3A12398%2F&
scope=user_read%20channel_read&
state=82hdknaizuVBfd9847guHUIhndzhuehnb
Again, make sure the state value is properly URL encoded.
3. Open the authentication URL
Ideally you just open the URL in a WebView inside of your app. In that case you need to intercept all request to load a new URL using WebViewClient.shouldOverrideUrlLoading
Once the client is redirected to your redirect URL you can close the webview and continue with step 4.
Theoretically it's possible to utilize the default browser to do the authentication, but I would have security concerns since an external app could learn about your client ID and the access token.
4. Extract the access token
The actual URL you get redirected to in step #3 will have the form:
https://[your registered redirect URI]/#access_token=[an access token]&scope=[authorized scopes]
or to pick up the example
https://localhost:12398/#access_token=xxx&scope=user_read%20channel_read
Where xxx is the actual access token.
If you passed a state it will be present like so:
https://localhost:12398/#access_token=xxx&scope=user_read%20channel_read&state=82hdknaizuVBfd9847guHUIhndzhuehnb
All you have to do now is to parse the (URL encoded) access token, scope and state. Compare the scopes and state to the ones that you actually sent. If they match you can start using the access_token to authenticate.
Note According to the OAuth2 RFC, the response URL MUST also contain a token_type and it SHOULD contain an expires_in duration in seconds.
Once you received the access token you can use it to authenticate as described here.
Access tokens issued by the Implicit Grant Flow usually expire after a certain time and the user needs to authenticate again. The Twitch documentation doesn't mention any expiration time, so it's possible that the token is valid forever. So make sure your app doesn't store it or store it in a secure way (like using Android's key store provider to generate and store a key to encrypt the access token).
If the implicitly issued access token expires you could consider using the "Authorization Code Flow". That's quite similar but it contains an additional step to receive the access token and a "refresh token" that can be used to renew the access token. I leave it up to you to figure out how that works.

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.

OAuth protocol / java- Scribe : storing the token?

I've been playing with the [scribe API][1] and a basic example e.g:
https://github.com/fernandezpablo85/scribe-java/blob/master/src/test/java/org/scribe/examples/TwitterExample.java
In a command line oriented interface, the user is asked to open a web-browser and to copy'n paste the "accessToken".
Once the user has copied the "accessToken", I want to avoid this "browser step" in the later invocations of the tool: can I store the "accessToken" somewhere to re-use it later ? would it work for any server (Twitter ? Flickr... ) ? How should I change the code to reuse the previously saved "accessToken" ?
Thanks,
In the case of the Twitter API you should store the access token as it represents the user's permission for your application to access their account.
However, bear in mind that the token may be revoked by the user, so ensure your application is able to obtain it again.
To change the code to use a previously saved accessToken all you would have to do is look up the token for the current user - perhaps it's retrieved from a database, and then start making requests. Essentially you would just skip the whole "obtaining request token" block of code.

Categories

Resources