In this post, I will walk through an example of integrating an OAuth2.0 authorization flow into an application. In this example, the third-party app that I am integrating with is TD Ameritrade.
What is OAuth2.0?
OAuth2.0 is a standard. For authorization. Used when you want to delegate authorization to your app/service to a third-party. Read more about it here.
What is TD Ameritrade?
TDA is a stockbroker. They let you create brokerage accounts for trading stocks, bonds, derivatives etc. They have feature heavy electronic platforms
for performing stock research, execute trades on the stock market and for managing stock portfolio. TDA also provides REST endpoints so that developers can programmatically access a certain subset of data from your trading accounts, instead of using TDA's apps.
What am I going to build in this exercise?
I want to build an app that makes use of TDA REST APIs to fetch my account details. To use the REST APIs for fetching account details, I need to pass some "password" to the REST API call. TDA has implemented an OAuth2.0 token-based authentication flow to generate these access "passwords" that you can use when using their REST APIs. In this exercise, I will walk through how to tame the authentication flow when working with TDA APIs.
Getting started
Here is a dictionary of terms that might be new to you and referenced in this article.
Glossary
Step 1: Registering a new app in TD Ameritrade
To use any of the TDA APIs, you first need to register an app with TDA. This gives you a unique client id which is used as part of the OAuth2.0 flow. Register at TDA for developers. Click on My Apps to create an app.
You are allowed to create only one app per user account.
Enter a name and description for the app. Call back URL is the URL that the app needs to go to once the authorization is completed. If you don't have an app yet, just put in any URL, for instance, https://localhost. In the Order Limit field, give a reasonable limit. For most hobby development activity 2 is more than enough.
Make a note of the Consumer Key that is generated. This will also be referred to as client_id later on.
Step 2: Get access code
The first step in building an automated authorization mechanism with the TDA REST APIs is to generate an access_token and a refresh_token for the very first time. You have the option of plugging in this flow into your application or performing this one-time step manually. In this exercise, we will do this manually.
1. Navigate to the Authentication URL in the browser. The format for this is as follows:
https://auth.tdameritrade.com/auth?response_type=code&redirect_uri=<enter callback url for your app>&client_id=<enter client id for app>%40AMER.OAUTHAPP
2. This would open up a page that will ask for your TD Ameritrade login credentials. Enter the details and click on Log In.
3. Once you log in, a page opens up asking for authorization to allow your registered app to have access to your TDA trading account. Click on Allow.
4. Once logged in, the browser would navigate to your app's redirect URL. The URL would contain a parameter with the name code. Copy the value of this parameter, i.e everything after code=.
https://<callback url>/?code=<access_token>
Example:
https://localhost/?code=2brLZda773S%2F4A8s77daAFaQDPgq%2Fb8GcNBQWu
In the above example, the callback URL of the app is https://localhost and the code to be copied is 2brLZda773S%2F4A8s77daAFaQDPgq%2Fb8GcNBQWu
5. This code needs to be URL decoded. You can use a site such as this to perform the decoding. Decoding the above example code yields the following result.
2brLZda773S/4A8s77daAFaQDPgq/b8GcNBQWu
Step 3: Get access token and refresh token for the first time
1. Now we need to get an access token and a refresh token for the first time. To get this, open up the Post Token API page in TDA. On this page, you can make sample test calls to the API. Use this feature to get the access_token and the refresh_token for the first time. You could also use a REST API management tool such as Postman to perform this step.
grant_type: authorization_code
refresh_token: <leave as null>
access_type: offline
code: <insert URL decoded code from above>
client_id: <insert client id>
redirect_uri: <call back url>
2. A successful request will return the following response
{
"access_token": "<access token that is valid for 30 minutes>",
"refresh_token": "<refresh token that is valid for 90 days>",
"scope": "PlaceTrades AccountAccess MoveMoney",
"expires_in": 1800,
"refresh_token_expires_in": 7776000,
"token_type": "Bearer"
}
Once you have the access token, you would use it to perform actions such as checking account balances and placing trades. For instance, to view your account, you can use the Get Account API either directly from this page or via a tool such as Postman. You just need to pass the access_token in the Header parameter called Authorization. The format needs to be Bearer followed by a space and then the access token. Access tokens are valid for 30 minutes. When the access token expires, you would use the refresh token to get a new access token issued.
Step 4: Refreshing access token
If you have a valid refresh token, use the following parameters with the Post Access Token API to create only an access token.
grant_type: refresh_token
refresh_token: <insert valid refresh token>
client_id: <insert client id or consumer key>
Step 5: Refreshing refresh token
Refresh tokens expire in 90 days. If the refresh token expires, you would need to start the process all over again, by navigating to the Authorization URL. Hence, it is a good practice to get a new refresh token issued before it expires. You can do this using the Post Access Token API using the below parameters.
grant_type: refresh_token
refresh_token: <insert valid refresh token>
access_type: offline
client_id: <insert client id or consumer key>
Integrate TDA authentication into your application and automating the token issue
Below is a process flow that can be built into your application to automate the process of getting new access and refresh tokens issued.
This workflow has been implemented on a trading app that was built using Oracle APEX on Oracle Autonomous Database Always Free Services.
What is Oracle APEX?
It is a tool using which you can build apps. You can build fully functioning apps with low to no programming. It also has the flexibility to allow you to write complex programming logic as well. It is available for free with Oracle database.
What is Oracle Autonomous Database?
It is a version of the Oracle database. It is installed and managed by Oracle. You can get 20GB of this database for free. Forever!
Comments