Additional Resources
Associating a user with their token
A possible way to associate a user with their token is to generate a cookie on the redirect_uri
endpoint of your application.
When the user attempts to make an API request your application will inspect the cookie and use that to query your token storage.
This can be done easily using the cookie-parser middle-ware for express
Caching API responses
To improve the response time of your web appliciation and limit external API requests is to cache API responses. For example you have an endpoint in your application which calls
AuthenticatorContext.authenticators(token)
Instead of calling this function, store the response whereby if the same user hits your endpoint within a certain time the stored response can be sent.
Redis will be used as the cache server.
Below are excerpts from an example NodeJS application using express and the ibm-verify-sdk which uses the strategy outlined above.
// Include and instantiate a redis client
var redis = require('redis');
var redisClient = redis.createClient();
// Display redis errors
redisClient.on("error", (err) => {
console.log("Redis Error: " + err);
});
// Returns the users registered authenticators
app.get('/api/authenticators', (req, res) => {
// Get requesters token
let token = getToken(req); // developer implementation
// The key for our cache entry - unique to the user
let key = '/api/authenticators/' + token['access_token'];
// How long the cache entry is valid (seconds)
let cacheExpiry = 10;
// Search redis for the key
redisClient.get(key, (err, reply) => {
// Response is present in cache
// Send back cached response
if (reply !== null) {
res.setHeader("Content-Type", "application/json");
res.send(JSON.parse(reply));
return;
}
// Not found in cache, perform the API request
AuthenticatorContext.authenticators(token).then(response => {
// Convert API response to a string
let response_str = JSON.stringify(response.response);
// Store response in cache
redisClient.set(key, response_str, 'EX', cacheExpiry);
// Send the response
res.setHeader("Content-Type", "application/json");
res.send(response_str)
}).catch(error => {
res.send("Error getting authenticators");
});
});
});