Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Stitch JWT custom auth: valid UID required (between 1 and 128 characters)

How to set a valid UID required (between 1 and 128 characters) for mongodb Atlas Cloud Stitch in node.js? I'm using jasonwebtoken package for sign the token of Stitch's credential:

Nodejs:

 var token = jwt.sign(payload, Buffer.from(key), options);
 credential = new CustomCredential(token);
 stitchclient.auth.loginWithCredential(credential)
 .then(authedUser => console.log(`logged in with custom auth as user ${authedUser.id}`))
 .catch( err => console.error(`failed to log in with custom auth: ${err}`))

I can send, passing signature but Stitch returns:

failed to log in with custom auth: StitchServiceError: invalid custom auth token: valid UID required (between 1 and 128 characters)

Ty for your time!

Documentation on: https://docs.mongodb.com/stitch/authentication/custom-token/#usage

like image 259
Tobjj Avatar asked Oct 17 '25 16:10

Tobjj


2 Answers

To be more specific, if you are for example generating the token from a Realm function, you will get the user id from the context :

exports = function(userMail) {
  const jwt = require('jsonwebtoken')
  const KEY_JWT = 'MY_SECRET_KEY'
  const token = jwt.sign({
                  email: userMail, 
                  sub: context.user.id,
                  aud: "<application_id>"
                },
                  KEY_JWT,
                {
                  expiresIn: "1h"
                }
            )
  return token
}
like image 153
S. Sylvain Avatar answered Oct 20 '25 07:10

S. Sylvain


Solved:

Set previusly on payload:

 "aud": "your api stitch id",
 "sub": "your user custom api key"
         var header = {
            alg: "HS256",
            typ: "JWT"
          }
          var payload = {
            "aud": "your api stitch id",
            "sub": "your user custom api key",
            name : "name",
            pass : "pass",
          } 
          var options = {
            expiresIn : (60 * 60 * 24).toString(), // ONE DAY TO EXPIRATION
            algorithm: 'HS256'
          } 

Later:

var token = jwt.sign(payload, Buffer.from("your user custom api key"), options);
credential = new CustomCredential(token);
stitchclient.auth.loginWithCredential(credential)
.then(authedUser => console.log(`logged in with custom auth as user ${authedUser.id}`))
.catch( err => console.error(`failed to log in with custom auth: ${err}`))
like image 23
Tobjj Avatar answered Oct 20 '25 06:10

Tobjj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!