Share login state between microservices

I assume that you have created a 2nd connection to your microservice using DDP.connect. e.g. I will call this 2nd connection mServiceConn

Then you have a connection. You can share logins with your login to your client server.

  1. Create a new Accounts client for the new connection via AccountsClient({'connection': mServiceConn})
  2. Get your client server login via Accounts._storedLoginToken(). This takes the token information out of the localStorage.
  3. Login to your new connection via the new accounts client mServiceAccount.loginWithToken(token, callback())

Snippet:

let mServiceConn= DDP.connect(MICROSERVICE_URL);
let mServiceAccount = new AccountsClient({'connection': mServiceConn});

// On login:
// - login to the client server through the Accounts package
// - login to the microservice server
Accounts.onLogin(() => {
  let loginToken = Accounts._storedLoginToken();

  // Use the accounts loginToken to login to the mService
  if(loginToken) {
    console.log('Logging in with token');
    mServiceAccount.loginWithToken(loginToken,
      (loginErr, result) => {
        if(loginErr) {
          console.log(loginErr.message);
        }
      });
  } else {
    console.log('Unable to log in');
  }
});

Good luck!

6 Likes