Navigation

Set up JWT Authentication with MongoDB Realm

On this page

  • Overview
  • Prerequisites
  • Procedure
  • Create a JWT Token
  • Enable JWT Authentication in Your Realm app
  • Update Your Client to Use JWT Authentication
  • Summary

In this tutorial, you will implement Custom JWT Authentication for your Realm app. You will learn how to:

  • Enable JWT Authentication
  • Use a third-party JWT provider to generate a valid token
  • Authenticate against the backend from a client application

This tutorial should take around 30 minutes.

  • Create a Realm app. If you have completed the Task Tracker tutorial, you can use that backend Realm app.
  • You can use any Realm app for this tutorial. If you do not have a test app you can use, download one of the Task Tracker apps from the tutorial.

This procedure is divided into three logical steps:

  1. Create a JWT token
  2. Enable and configure JWT Authentication in Realm
  3. Add authentication code to your client app

For this tutorial, we will use a third-party website, jwt.io, to generate a JWT token.

Go to jwt.io. Scroll down until you see the Encoded and Decoded headers. In the Decoded column, you will see three sections that comprise a JWT token: Header, Payload, and Verify Signature areas, each of which is explained in the next sections.

The header of a JWT informs consuming applications what algorithm was used to encode the token. The default, which we will use for this tutorial, is HS256.

Note

For more information on JWT algorithms, see JSON Web Token (JWT) Signing Algorithms Overview. Realm supports HS256 and RS256.

The Payload section contains the information that we need to configure for our Realm-specific needs. By default, three fields are included: sub, name, and iat. We will use these three, plus two more fields. The following table explains each field and the value expected:

Field
Description
Value
sub
The subject of the jwt, which you set according to your business needs. For more information, see RFC 7519 4.1.2.
<your email or any other unique value>
name
The name of the user to whom this JWT is assigned. If specified, Realm uses this value as the user's display name. Optional.
<your name>
iat
"Issued At" is a Unix epoch timestamp of when the token was issued.
The current date-time in seconds since Unix epoch.
exp
The date-time when this token will expire.
A future date-time (in seconds since Unix epoch) for when you want the token to expire. Depending on your business needs, this can be any duration.
aud
The audience (consumer) of the token.
Your Realm App ID, which you can find in the Realm UI.

For this tutorial, we have created a JWT for a user named "Caleb". The token was issued at the time of writing and will expire in exactly 1 year, and is intended to be used by a Realm with an ID of "boiboi-cul8r". Our completed JSON payload looks like this:

{
"sub": "1234567890",
"name": "Caleb",
"iat": 1617313420,
"exp": 1648849420,
"aud": "boiboi-cul8r"
}

The final step in creating the JWT is to add a 256-bit secret with which the token is encoded. In this last section, find the field with the placeholder text of "your-256-bit-secret". Paste in any 256-bit string value into this field. If you are uncertain what value to use, consider visiting a random key generator website, like keygen.io, and copy one of the 256-bit values that has been generated.

Important

The key you use must only contain ASCII letters, numbers, underscores, and hyphens, and must be between 32 and 512 characters long.

Note

Keep track of this secret, as you will need it in the next section when we configure Realm authentication.

After pasting in your key, check the secret base64 encoded check box.

At this point, you have generated a JWT key that can be used with — and only with — the Realm app you specified. Copy this key from the Encoded box and temporarily save it in a text document. Your JWT will be 3 sections of values, separated by periods, and looks something like the following (your token will not match this!):

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. ⤶
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkNhbGViIiwiaWF0IjoxNjE3MzEzNDIwLCJle ⤶
HAiOjE2NDg4NDk0MjAsImF1ZCI6ImJvaWJvaS1jeWFsOHIifQ. ⤶
GaIE4e6mGxlIBNnz4FcheFBUmxd25GK-rfOfF6F85rY

If you are not currently logged in to Realm do so now and navigate to the Realm app that you specified when generating the JWT in the previous section.

  1. In the left-hand navigation, under Data Access, select Authentication.
  2. Select the Authentication Providers tab.
  3. Near the bottom of the list of providers, select Custom JWT Authentication.
  4. Use the following table to set the properties on this page:

    Field
    Value
    Provider Enabled
    Select to enable
    Verification Method
    Manually specify signing keys
    Signing Algorithm
    HS256
    Signing Key (Secret Name)

    Provide a name that will have some meaning to you (for example, "newKey"), and then click the box that appears immediately below the name that reads "Create <key name>".

    In the resulting Signing Key text box, paste in the 256-bit key that you used when generating the JWT in the previous section. Do not click the "Add Singing Key" button.

    Warning

    A Signing Key is a secret key and anyone with the key can issue valid user credentials for your app. Ensure that it's never stored in a publicly accessible location, such as a git repository, message board, or in your code.

    Metadata Fields (Optional)
    Leave blank
    Audience (Optional)
    Leave blank.
  5. When you have set all of the values, click Save. If you are prompted at the top of the screen to do so, review and deploy your changes.

The final step in this tutorial is to update your client application to use JWT authentication. The Realm SDKs make this process straightforward, and while each language has its own specific implementation, the pattern they each use is the same: pass the generated token to a login call:

Implementing a custom JWT authentication provider involves:

  • Generating a valid JWT token that includes the Realm app ID in the payload
  • Enabling the authentication provider in Realm
  • Adding the authentication logic to your client
Give Feedback

On this page

  • Overview
  • Prerequisites
  • Procedure
  • Create a JWT Token
  • Enable JWT Authentication in Your Realm app
  • Update Your Client to Use JWT Authentication
  • Summary