Search code examples
mongodbjwtcustom-authenticationmongodb-stitch

How Custom Authentication Works in MongoDB Stitch


Following MongoDB Custom Authentication, it is given that any JWT Token with the minimal below fields works with the MongoDB Stitch Authentication. Also, token needs to be issued by External Authentication System

{
  "aud": "<stitch app id>"
  "sub": "<unique user id>",
  "exp": <NumericDate>,
}

I've tested this and it works as well

  1. Created Stitch App and enabled Users with Custom Authentication Provider
  2. Generated Sample Token through Jwt.io with the below inputs. (Use same algorithm and key as configured when enabling Custom Authentication Provider, Here it is, HS256 and the )

enter image description here

It works in the way,

  • It is validating the users in MongoDB Stich Users Collection with the unique value provided in sub: "sub": "<unique user id>" and if the user is present then it returning the Object Id for that User.
  • If the user is not present then it is creating one against the input and returning the Object Id.

Queries are,

  1. Why it is creating a new user instead of returning login failure, which in turn works like any user can log in with any credentials on demand?
  2. If MongoDB Stitch Custom Authentication involves External Authentication System to issue JWT, where the user data will be actually stored when user registration? - MongoDB Stitch App Collection or External Authentication API System?

Solution

  • Here is the response from MongoDB Support

    Why is Stitch creating a new "User"

    The "User" Stitch creates in this scenario is an internal user. This "user" also contains the user data and metadata provided from the JWT and is not stored alongside your other collections in the Atlas cluster your application is linked against. Note that this "user" is not accessible to MongoDB without using a trigger or other function to load it into the database.

    Why isn't a login failure returned

    A login failure is not being returned because the custom authentication provider is only checking the signed JWT from the external system against its own copy of the signing key. If the signatures match then the login is deemed successful.

    It is the responsibility of the external authentication provider to fail the login; not Stitch.

    Where will the user data actually be stored

    The user data should be managed within your database. The most efficient way to integrate this with the Custom Authentication provider is to use an Authentication Trigger on Create and/or Login operation types. This would allow you to run a Stitch Function any time an authentication event is triggered.

    There is an example of using authentication triggers on the MongoDB blog which may help explain the process further.