Is this how to get the refresh token from the msal-node library?
I'm not sure if that will work. It looks like it will but you will still need to handle the actual refresh process once you have the token. You may be able to use the .acquireTokenByRefreshToken()
method of the ConfidentialClientApplication object, documented here, but according to the documentation that is not the way Microsoft intends this library to be used, and if you rely on this kind of unsupported workflow, your code is susceptible to unexpectedly breaking if Microsoft changes anything.
How do I refresh the token after some time?
In msal-node, the developer is not intended to do this themselves. See this github issue for a discussion. The library caches the tokens it receives, and you are intended to use them like this:
const someUserHomeAccountId = "Enter_User_Home_Account_Id";
const msalTokenCache = cca.getTokenCache();
const account = await msalTokenCache.getAccountByHomeId(someUserHomeAccountId);
const silentTokenRequest = {
account: account,
scopes: ["user.read"],
};
cca.acquireTokenSilent(silentTokenRequest).then((response) => {
// do something with response
}).catch((error) => {
// catch and handle errors
});
In this example (which is just copied from this very informative link) cca
is the equivalent of your ouathClient
variable.
By default, the token caching just occurs in memory.
Unfortunately, this is not appropriate for production applications, because the in-memory caching will only persist the token data for the lifetime of the MSAL instance, which means you will lose your tokens if the process ever restarts. And if your server runs as multiple processes, they must share memory.
The caching is configured when you create the PublicClientApplication or ConfidentialClientApplication object. cache
is an optional property of the Configuration object that the client constructor takes in. The page where I took the above example code from has a detailed discussion of how to implement your own caching solution that matches the protocol of the msal-node library.
There is an official extension library (github repo has better docs) that has a solution to persist the cache to disk, but its intended purpose is PublicClientApplications.
For ConfidentialClientApplication instances running on a server, the best solution is to implement an L1/L2 cache where the L2 is a distributed store like Redis (source). For something slightly simpler (only have the currently served user's tokens in memory), you can go to the msal-node-samples and look at the ExpressTestApp example, which implements persistent caching with Redis.