Best practice for sending generated token from server to client


#1

Hello All ,

I am generating token for user using Accounts package

const stampedLoginToken = Accounts._generateStampedLoginToken()
Accounts._insertLoginToken(user._id, stampedLoginToken)

and sending token to client in a redirect url, which is a security concern.

res.writeHead(302, { location: /?token=${stampedLoginToken.token} })

and extracting token on client, this is a big no no but some guy wrote code and now i am fixing it

How are you guys sending it to client?
I am looking for a best practice please give some suggestions


#2

Hi @saig

We do have a scenario in our app where a user is authenticated against a third party system and we need to log them in to our app on success.

We just call a server method from our app and return the stamped access token in the return value…

i.e. on server:

Meteor.method('user.auth.token', type, receipt) {
          // Validate the user against the 3rd party system using type and receipt...

          // On success... log the user in
          const accessToken = Accounts._generateStampedLoginToken();

          Accounts._insertLoginToken(user._id, accessToken);

          return resolve({ success: true, token: accessToken.token });

          // On failure... return reason

          return resolve({ success: false, error: "xxx" });

}

On client:

   Meteor.callPromise('user.auth.token', type, receipt).then(response => {
      if (response.success === false) {
          // Error handling
     } else {
          // It worked - log the user in and take them to the /home page
        Meteor.loginWithToken(response.token, function(loginTokenErr) {
          if (loginTokenErr) {
            swal({
              showConfirmButton: true,
              title: 'Restoring Purchase...',
              allowOutsideClick: false,
              text: 'Login failed after restore purchase. Please try again.',
            }).catch(swal.noop);
          } else {
            browserHistory.push('/home');
          }
        });

Hope this helps.

And hey - I’m happy to help you and to more generally help out on the forum as I’m able - however please keep in mind that I don’t work for MDG… :slight_smile: - keep the questions open to everyone rather than directed to me personally - the wider Meteor community will then be more likely to jump in and assist too.