Verification
A common use case is that you authenticate the user on the client, but you want to also validate this token as well as corresponding user information on your backend. In this case, Sequence provides a function to retrieve a JWT which can be verified using your JWT library of choice for your given framework. Below we outline an example using Typescript and an express server.
Implementation
Request IdToken via Client
Once a user has authenticated with an embedded wallet on the client, simply call the corresponding function in order get a JWT from Sequence.
const { idToken } = await sequence.getIdToken();
Pass JWT to Backend
Make a POST request to your backend with the queried JWT.
const response = await fetch(BACKEND_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ sequenceToken: idToken }),
});
Import JWT libraries and initialize JWKS
From our express server that the JWT was passed to, we simply import our preferred JWT library to verify the information and initialize our JWKS to verify against. It is also important to ensure that your expected audience is set correctly so that the claim will be properly verified.
import * as jwt from "jsonwebtoken";
import * as jwksClient from "jwks-rsa";
...serverConfig
// Initialize the JWKS client
const client = jwksClient({
jwksUri: "https://waas.sequence.app/.well-known/jwks.json",
cache: true,
cacheMaxAge: 86400000, // 1 day
});
// Should be equal to the audience claim in the JWT that you want to verify which will be of the form https://api.sequence.build/project/*projectID*
const EXPECTED_AUDIENCE = "https://api.sequence.build/project/*PROJECT_ID*"
Decoding JWT and Verifying Claims
Now we can parse the JWT, verify it against our JWKS URI, then validate any of the claims.
const decodedToken = jwt.decode(token, { complete: true });
if (!decodedToken || typeof decodedToken === "string") {
throw new Error("Invalid token");
}
const kid = decodedToken.header.kid;
const signingKey = await getSigningKey(kid);
const publicKey = (
signingKey as jwksClient.CertSigningKey | jwksClient.RsaSigningKey
).getPublicKey();
console.log(EXPECTED_AUDIENCE);
const verified = jwt.verify(token, publicKey, {
algorithms: ["RS256"], // Specify the expected algorithm
audience: EXPECTED_AUDIENCE, // Verify the audience claim
});
// Verifying Email claim
if (!verified.email || typeof verified.email !== "string") {
throw new Error("Invalid email claim");
}
Update your backend
From here, you now have verified the information corresponding to the JWT and can safely update your backend as needed.