Skip to main content

Creating a token

When you create a token, you need to ensure that the key used to generate it, is stored in a safe place, to mitigate any jwt based attack. Use of HS256 is not recommended as it's using a single string to forge the web token and it can easily be brute-forced compared to more modern algorithms such as RS256.
Here is below an example to create a JSON Web Token for the selected algorithm:

import {generatePrivateJwk, createSignedJwt} from "@authdog/easyjwt"
const main = async () => {    const payload = {        userId: "e156b806-2879-4f4b-878d-9426d75dbcbf"    }
    const algorithm = "RS256";
    const jwk = await generatePrivateJwk(        "RSA",        algorithm    );
    const token = await createSignedJwt(        payload,        {            algorithm,            claims: {                issuer: "",                audiences: ["users", "app", "dashboard"],                scopes: "user openid",                sessionDuration: 60 // minutes            },            signinOptions: {                jwk            }        }    );
    // ...    // do something with the token

The token should have self-contained headers and payload as below:

{  "alg": "RS256",  "typ": "JWT"}
{  "userId": "e156b806-2879-4f4b-878d-9426d75dbcbf",  "iat": 1626934547,  "exp": 1626938147}