Custom JWT Authentication¶

司马庆
2023-12-01

MongoDB Logo
ServerDriversCloudToolsGuides
Get MongoDB
Close ×
MongoDB Stitch

Introduction
Tutorials
Users & Authentication
    Overview
    User Management
        Stitch Users
        Configure Custom User Data
        Finding a User
        Viewing User Data
        Managing User Accounts
        Linking User Accounts
        Working with Multiple User Accounts
    Authentication Providers
        Overview
        Anonymous
        Email/Password
        API Key
        Apple ID
        Facebook OAuth 2.0
        Google OAuth 2.0
        Custom Function
        Custom JWT
MongoDB Atlas
GraphQL
MongoDB Mobile
Functions
Triggers
External Services
Values & Secrets
Application Deployment
Hosting
Troubleshooting
Stitch Administration
Application Logs
Client SDKs
Release Notes

Stitch > Users & Authentication > Authentication Providers 

Custom JWT Authentication

On this page

Overview
Configuration
    Audience
    Verification Method
    Metadata Fields
Usage
    Authenticate a User
    JSON Web Tokens

Overview

The Custom JWT authentication provider allows users to authenticate with an authentication system that is independent from Stitch. The external system must return a signed JSON Web Token that contains a unique ID value for the authenticated user.

Stitch uses the JWT to identify your application’s users and authenticate their requests but does not impose any restrictions on the external authentication system’s requirements or authentication methods. For example, the system could require the user to perform two factor authentication, provide specific credentials, or otherwise identify themself.
Diagram of Custom JWT authentication architecture.
Configuration

Stitch UI Import/Export 

You can enable the JWT authentication provider from the Stitch UI by selecting Custom JWT Authentication from the Users > Providers page.

You can configure the following properties for the provider:

Audience
Verification Method
Metadata Fields

Audience

The Audience of a JWT specifies its intended recipient. JWTs describe their audience in the aud claim. By default, Stitch expects aud to contain the App ID of the Stitch app for which the provider is configured.

If the external authentication system JWT specifies a different aud value, then you can configure the provider to use that value instead.

Stitch UI Import/Export 

To override the default audience, specify a new value in the Audience input:
The Custom JWT audience configuration input
Verification Method

The Verification Method configures how the provider determines which signing algorithm and signing keys the external authentication system must use to sign each JWT.

You can either manually specify signing keys or specify a JSON Web Key URI.
Manually Specify Signing Keys

You can manually configure the signing algorithm and specify one or more signing keys that the external authentication system may use to sign JWTs.

Stitch UI Import/Export 

Field Description

Signing Algorithm

The cryptographic method that the external system uses to sign the JWT. Custom authentication supports JWTs signed using any of the following algorithms:

HS256
RS256

The Signing Algorithm configuration dropdown
click to enlarge

Signing Key

A list of the names of up to three Secrets that each contain a signing key used by the external authentication system to sign JWTs. Each signing key Secret must be a string with length between 32 and 512 characters.
The Signing Keys configuration inputs
click to enlarge

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.
Use a JWK URI

Some external authentication systems provide a JSON Web Key Set that describes the signing algorithm and signing keys the system uses to sign JWTs. You can use the JWKS to configure the provider instead of manually specifying the signing algorithm and keys.

Stitch UI Import/Export 

Field Description

Use JWK URI
If true, configures Stitch to use a signing algorithm and signing keys defined in a JWK or JWKS. The JWKS must be accessible at a URL that you specify.

JWK URI

A URL that hosts a JWK or JWKS that describes the signing method and signing keys the JWTs should use. The JWKS may specify up to three signing keys and must use the RS256 algorithm.
The JWK URI input
click to enlarge
Metadata Fields

Metadata Fields are additional data that describe each user. Stitch determines the value of each metadata field from the value of some field included in the JWT from the external authentication system. Stitch refreshes a user’s metadata whenever they log in and exposes the fields in the data object of the user object.

Stitch UI Import/Export 

To define a metadata field, click Add Field and specify the mapping between the metadata field in the JWT and its corresponding field name in the user object.
The metadata fields configuration table
Field Description

Required
If true , the metadata field is required for all users associated with the provider, i.e. the JWT returned by the external system must have a value assigned to the field designated by Path.

Path
The name of a field in the JWT that contains the value for the metadata field. To specify a field in an embedded object, use dot notation.

Field Name

Optional. A name for the field in the user object’s data document that exposes the metadata field value. If not specified, this defaults to the same name as the JWT field that contains the value. The metadata field name may not contain no more than 64 characters.

For example, if you specify a name of location.primary.city, the default value for field_name is city.

Example

An external authentication system returns JWTs that include additional information about each user in the user_data field:

{
“aud”: “myapp-abcde”,
“exp”: 1516239022,
“sub”: “24601”,
“user_data”: {
“name”: “Jean Valjean”,
“aliases”: [
“Monsieur Madeleine”,
“Ultime Fauchelevent”,
“Urbain Fabre”
]
}
}

To include the values from the user_data field in each user’s user object, you could specify the following metadata fields:
Path Field Name
user_data.name name
user_data.aliases aliases

We can now access the mapped values directly from the user object, which would resemble the following for the given JWT:

{
“id”: “59fdd02846244cdse5369ebf”,
“type”: “normal”,
“data”: {
“name”: “Jean Valjean”,
“aliases”: [
“Monsieur Madeleine”,
“Ultime Fauchelevent”,
“Urbain Fabre”
]
},
identities: [
{
“id”: “24601”,
“provider_type”: “custom-token”,
“data”: {
“name”: “Jean Valjean”,
“aliases”: [
“Monsieur Madeleine”,
“Ultime Fauchelevent”,
“Urbain Fabre”
]
},
}
]
}

Usage
Authenticate a User

JavaScript SDK Android SDK iOS SDK 

To log a user in to your app with the Custom JWT authentication provider, call StitchAuth.loginWithCredential() with an instance of CustomCredential created with a signed JWT from the external authentication system.

const jwtString = getTokenFromCustomBuiltAuthSystem();
const credential = new CustomCredential(jwtString);

Stitch.defaultAppClient.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}))

JSON Web Tokens

The external authentication system must return a JSON web token that uniquely identifies the authenticated user. JSON web tokens are an industry standard (RFC 7519) for securely representing claims between two parties. A JWT is a string that consists of three parts: a header, a payload and a signature and has the following form:

..

Header

The header portion of the JWT consists of a Base64UrlEncoded document of the following form:

{
“alg”: “HS256”,
“typ”: “JWT”
}

Field Description

alg

Required. A string representing the hashing algorithm being used.

Stitch supports JWTs encoded with the following algorithms:
Algorithm Value
HMAC SHA-256 “HS256”
RSA Signature SHA-256 “RS256”

typ

Required. The type of the token. Stitch expects a JSON web token so the value should be "JWT".

Payload

The payload portion of the JWT consists of a Base64UrlEncoded document of the following form:

{
“aud”: “”
“sub”: “”,
“exp”: ,
“iat”: ,
“nbf”: ,

}

Field Description

aud

Required. The audience of the token. By default, Stitch expects this value to be the App ID of your Stitch application. If your external authentication service returns a different aud value, you should specify that value instead.

sub

Required. The subject of the token. The value should be a unique ID for the authenticated user from your custom-built authentication system.

exp

Required. The Expiration date of the token. The value should be a NumericDate number indicating the time at which the token expires.

Note

MongoDB Stitch will not accept expired authentication tokens.

iat

Optional. The “issued at” date of the token . The value should be a NumericDate number that indicates the time after which the token is considered valid. This field is functionally identical to nbf.

nbf

Optional. The “not before” date of the token. The value should be a NumericDate number that indicates the time before which the token is considered invalid. This field is functionally identical to iat.

Note

Stitch ignores any additional fields in the JWT payload unless you have mapped them to metadata fields in the provider configuration. Stitch includes the values of mapped fields in the data document of the authenticated user’s user object.
Signature

The signature portion of the JWT is a hash of the encoded token header and payload. To form the signature, concatentate the encoded header and payload with a period and sign the result with the Signing Key specified in the authentication provider configuration using the hashing algorithm specified in the “alg” field of the header.

HMACSHA256(
base64UrlEncode(header) + “.” + base64UrlEncode(payload),
signingKey
)

← Custom Function Authentication MongoDB Atlas Overview →

© MongoDB, Inc 2008-present. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.
Was this page helpful?
Yes
No

 类似资料:

相关阅读

相关文章

相关问答