It is common for an authentication system to generate long lasting tokens to perform multiple requests. In API Fortress there are many paths of authenticating that can be taken, but sometimes users prefer the token reuse strategy.
In this example we are showing you how to allow a test to store a token for further executions, and refresh it when it’s time. Each test will need to contain this logic, and each token will be bound to the test itself.
Here’s the complete test. Have a quick look at it before proceeding to the steps:
Prepare the input set by adding the basePath, loginPath, and dataPath. Most importantly, add an empty variable for token and expires. These items will be updated by the test.
Add an IF component with this logic:!expires || D.nowMillis()>expires.toLong()
Within the IF branch, make the login call. Shown here is a call to the login URL. We are storing the retrieved information in the variable named “loginPayload."
Within the IF branch, set the value to token and expires. Note that in the value we’re saying: take the current time and add one hourD.plusHours( D.nowMillis(), 1 )
Within the if branch, update the input set. This is a unique feature of API Fortress. By performing this operation, you’re having the test modify itself for the next use by updating the token and the expires variables. By doing so, the token will be available for all tests executions that will happen within an hour, and therefore no login calls will be made.
After the IF branch, perform the main call. We can reference the previously updated token.
When running outside the workbench, two subsequent test executions will look like this:
The whole operation might seem a bit annoying to replicate in every test, but the code view and some copy and paste can ease the pain.
Keep in mind this is just an example, and the calls are meant to be very simple. The following is the code version of the IF branch containing the authentication logic.
Updating input variables won't work when launching a test from within the composer, so the login call will run every time when developing a test. Run the test from outside the composer or schedule the test to see it in action.
- Negation: the exclamation mark (
!) prior to an expression is used as a negation and it means: when it’s false, when it’s empty, when it does not exist. In our example: !expires means when expires is empty.
- Logic Or: the classic double pipe sign (
||). Rarely used in API Fortress except in IF conditions.
toLong(): converts a string to a long number.
D.<action>()an API Fortress language extension that provides date and time manipulation functionalities. Please refer to the expression language extensions page for further details.