I have a NodeJS Express Application that authenticates to an Auth Server via client credentials grant. The token that I receive is used to load data from an API.
What is the best practice to store the token across the application?
Note that the JWT is not user specific, since my Express App is the Client.
The Client Credentials grant is used when applications request an access token to access their own resources, not on behalf of a user.
To configure the authentication via the client credentials grant type and retrieve the access token: Provide your Request URL. Send a POST request with the following body parameters to the authorization server: grant_type with the value client_credentials.
The Client ID and Client Secret need to be encoded to Base64, using the UTF-8 character set, in the form of client_id:client_secret. A resource you can use for this purpose is https://www.base64encode.org/. This string is then passed as the Authorization header.
I will store it in memory. Normally I will write a singleton module to handle it.
auth.js:
class Auth {
getToken() {
// check if we has token already and that token isn't expired
if (this.token && !isExpired(this.token)) {
return Promise.resolve(this.token);
}
// if not we call API for the new token then return the new token
return asyncCallApiForToken();
}
}
module.exports = new Auth();
main.js
const auth = require('./auth.js)
auth.getToken()
.then(token => {
// we got token here
}
I'd try to avoid persisting the returned token and only keep it in-memory, as the client credentials grant enables you to fetch a new token relatively easily, and without user interaction.
But if that's problematic, then I'd say: Next to the client credentials, since the client credentials are at least as sensitive as the JWT token.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With