“Custom JWT Authentication”(自定义 JWT 身份认证)是指在 Web 应用或 API 中

张开发
2026/4/5 22:10:15 15 分钟阅读

分享文章

“Custom JWT Authentication”(自定义 JWT 身份认证)是指在 Web 应用或 API 中
“Custom JWT Authentication”自定义 JWT 身份认证是指在 Web 应用或 API 中不依赖现成的认证框架如 Django REST Framework 的TokenAuthentication或 Spring Security 的默认 JWT 支持而是手动实现 JWTJSON Web Token的生成、签名、验证、刷新及权限控制等全流程。核心步骤通常包括用户登录时校验用户名/密码 → 生成 JWT含 payload 如user_id,exp,iat,role等→ 使用密钥HS256/RSA签名 → 返回给客户端请求鉴权时从Authorization: Bearer token提取 token → 验证签名、过期时间、签发者等 → 解析出用户身份 → 绑定到请求上下文如request.user可选增强支持 token 刷新Refresh Token、黑名单登出、多设备会话管理、自定义 claim 权限检查如scope: admin:delete等。常见技术栈示例PythonFlask/FastAPI使用PyJWT手动 encode/decodeNode.jsExpress使用jsonwebtoken库JavaSpring Boot结合jjwt-api 自定义OncePerRequestFilter.NET使用Microsoft.IdentityModel.Tokens手动构建JwtSecurityTokenHandler。⚠️ 安全注意必须使用强密钥如 256 位随机 secret 或 RSA 私钥、设置合理exp、避免在 JWT 中存放敏感信息、始终校验aud/iss如适用、防范令牌泄露与重放攻击。# FastAPI 示例简易自定义 JWT 认证无第三方依赖fromdatetimeimportdatetime,timedeltaimportjwtfromfastapiimportDepends,HTTPException,statusfromfastapi.securityimportHTTPBearer,HTTPAuthorizationCredentials SECRET_KEYyour-super-secret-jwt-key-change-in-prodALGORITHMHS256security_schemeHTTPBearer()defcreate_access_token(user_id:int,expires_delta:timedeltatimedelta(hours1)):expiredatetime.utcnow()expires_delta to_encode{sub:user_id,exp:expire}returnjwt.encode(to_encode,SECRET_KEY,algorithmALGORITHM)defverify_token(credentials:HTTPAuthorizationCredentialsDepends(security_scheme)):try:payloadjwt.decode(credentials.credentials,SECRET_KEY,algorithms[ALGORITHM])user_id:intpayload.get(sub)ifuser_idisNone:raiseHTTPException(status_codestatus.HTTP_401_UNAUTHORIZED,detailInvalid token)returnuser_idexceptjwt.ExpiredSignatureError:raiseHTTPException(status_codestatus.HTTP_401_UNAUTHORIZED,detailToken expired)exceptjwt.InvalidTokenError:raiseHTTPException(status_codestatus.HTTP_401_UNAUTHORIZED,detailInvalid token)Custom JWT Authentication¶MongoDB LogoServerDriversCloudToolsGuidesGet MongoDBClose ×MongoDB StitchIntroduction 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 ProvidersCustom JWT AuthenticationOn this pageOverview Configuration Audience Verification Method Metadata Fields Usage Authenticate a User JSON Web TokensOverviewThe 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.ConfigurationStitch UI Import/ExportYou 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 FieldsAudienceThe 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/ExportTo override the default audience, specify a new value in the Audience input:The Custom JWT audience configuration inputVerification MethodThe 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 KeysYou 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/ExportField DescriptionSigning AlgorithmThe cryptographic method that the external system uses to sign the JWT. Custom authentication supports JWTs signed using any of the following algorithms:HS256 RS256The Signing Algorithm configuration dropdownclick to enlargeSigning KeyA 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 inputsclick to enlargeWarningA 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 URISome 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/ExportField DescriptionUse JWK URIIf 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 URIA 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 inputclick to enlargeMetadata FieldsMetadata 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/ExportTo 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 tableField DescriptionRequiredIf 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.PathThe 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 NameOptional. 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.ExampleAn 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 Nameuser_data.name nameuser_data.aliases aliasesWe 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”]},}]}UsageAuthenticate a UserJavaScript SDK Android SDK iOS SDKTo 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 TokensThe 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:..HeaderThe header portion of the JWT consists of a Base64UrlEncoded document of the following form:{“alg”: “HS256”,“typ”: “JWT”}Field DescriptionalgRequired. A string representing the hashing algorithm being used.Stitch supports JWTs encoded with the following algorithms:Algorithm ValueHMAC SHA-256 “HS256”RSA Signature SHA-256 “RS256”typRequired. The type of the token. Stitch expects a JSON web token so the value should be JWT.PayloadThe payload portion of the JWT consists of a Base64UrlEncoded document of the following form:{“aud”: “”“sub”: “”,“exp”: ,“iat”: ,“nbf”: ,…}Field DescriptionaudRequired. 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.subRequired. The subject of the token. The value should be a unique ID for the authenticated user from your custom-built authentication system.expRequired. The Expiration date of the token. The value should be a NumericDate number indicating the time at which the token expires.NoteMongoDB Stitch will not accept expired authentication tokens.iatOptional. 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.nbfOptional. 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.NoteStitch 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.SignatureThe 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 →

更多文章