How to use the sign function from jsonwebtoken

Find comprehensive JavaScript jsonwebtoken.sign code examples handpicked from public code repositorys.

jsonwebtoken.sign is a function that creates a JSON Web Token (JWT) by encoding a payload into a token string signed with a secret or private key.

252
253
254
255
256
257
258
259
260
261
  }
  return { user: await User.query().findOne({ email: userObj.email }), first_time_login };
}

createToken = (user) => {
  const JWTtoken = JWT.sign({ id: user.id, email: user.email }, CONFIG.auth.jwt.secret, {
    algorithm: 'HS256',
    expiresIn: CONFIG.auth.jwt.expiresIn,
  });
  return JWTtoken;
fork icon18
star icon15
watch icon4

+ 4 other calls in file

181
182
183
184
185
186
187
188
189
190
  dateselector: dateselector,
  type: passData.data[0].type,
  parkSk: passData.data[0].pk.split('::')[1]
};
logger.info("Signing JWT");
const token = jwt.sign(claims, process.env.JWT_SECRET, { expiresIn: '15m', algorithm: ALGORITHM });

const cancellationLink =
  process.env.PUBLIC_FRONTEND +
  process.env.PASS_CANCELLATION_ROUTE +
fork icon10
star icon7
watch icon7

+ 3 other calls in file

How does jsonwebtoken.sign work?

The jsonwebtoken.sign function is used to create a JSON Web Token (JWT) by encoding a payload into a token string signed with a secret or private key. To use jsonwebtoken.sign, you pass it a payload object, a secret or private key, and some options. The payload object contains data that you want to encode into the JWT, such as a user ID or other identifying information. The secret or private key is used to sign the JWT and prevent tampering. The options object can include various settings for the JWT, such as its expiration time or the algorithm used to sign it. Once you've set up the payload object, secret or private key, and options, you can call jsonwebtoken.sign to create the JWT. The function returns a string that represents the JWT. Here's an example of how to use jsonwebtoken.sign: javascript Copy code {{{{{{{ const jwt = require('jsonwebtoken'); const payload = { userId: '123', name: 'John Doe' }; const secretKey = 'my-secret-key'; const options = { expiresIn: '1h' }; const token = jwt.sign(payload, secretKey, options); console.log(token); // a string representing the JWT In this example, we create a payload object with some identifying information, a secretKey string to sign the JWT, and an options object that sets the JWT to expire in one hour. We then call jsonwebtoken.sign with these parameters to create the JWT. This code demonstrates how to use jsonwebtoken.sign to create a JSON Web Token (JWT) by encoding a payload into a token string signed with a secret or private key.

214
215
216
217
218
219
220
221
222
223
    expiresIn: config.get('tokenGenerate:expiresIn') || '30m',
    algorithm: 'RS256'
  };

  const privateKey = config.get('tokenGenerate:privateKey');
  const uiToken = jsonwebtoken.sign({}, privateKey, signOptions, null);
  log.verbose('Generated JWT', uiToken);
  return uiToken;
},
isValidUiTokenWithRoles: partial(isValidUiToken, isUserHasRoles),
fork icon5
star icon5
watch icon10

+ 5 other calls in file

117
118
119
120
121
122
123
124
125
126

// bhajeo otp

if (user) {
    if (user.otp === body.otp) {
        const token = jwt.sign({ _id: user._id }, process.env.SECRET);
        body.token = token;
        const loggeduser = await userModel.findOne({ phone: body.phone }, body);
        return {
            statusCode: 200,
fork icon0
star icon3
watch icon1

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const jwt = require("jsonwebtoken");

const payload = {
  userId: "123",
  name: "John Doe",
};

const secretKey = "my-secret-key";

const options = {
  expiresIn: "1h",
};

const token = jwt.sign(payload, secretKey, options);
console.log(token);

In this example, we create a payload object with some identifying information, a secretKey string to sign the JWT, and an options object that sets the JWT to expire in one hour. We then call jsonwebtoken.sign with these parameters to create the JWT. The output of this code will be a string representing the JWT.

39
40
41
42
43
44
45
46
47
48
get: {
    '/api/email/unsubscribe/{token}': [
        {
            in: 'path',
            name: 'token',
            example: (() => jwt.sign({
                template: 'digest',
                uid: 1,
            }, nconf.get('secret')))(),
        },
fork icon0
star icon2
watch icon5

+ 3 other calls in file

279
280
281
282
283
284
285
286
287
288

if (unsubscribable.includes(template)) {
    if (template === 'notification') {
        payload.type = params.notification.type;
    }
    payload = jwt.sign(payload, nconf.get('secret'), {
        expiresIn: '30d',
    });

    const unsubUrl = [nconf.get('url'), 'email', 'unsubscribe', payload].join('/');
fork icon0
star icon2
watch icon5

+ 3 other calls in file

40
41
42
43
44
45
46
47
48
49
  // SENHA INCORRETA
  return res.render("index", { user, className: "" });
}

// SENHA CORRETA
const token = jwt.sign({ user }, process.env.PROJECT_V_TOKEN_SECRET, {
  expiresIn: `${process.env.PROJECT_V_JWT_DURATION}s`,
});

res.cookie("token", token, { httpOnly: true }).redirect("/perfil");
fork icon0
star icon1
watch icon1

+ 4 other calls in file

30
31
32
33
34
35
36
37
38
39
  httpOnly: true,
};

// console.log(newUser, "newUser");

const accessToken = jwt.sign(
  {
    id: newUser._id,
  },
  process.env.ACCESS_SECRET,
fork icon0
star icon1
watch icon1

+ 4 other calls in file

106
107
108
109
110
111
112
113
114
115
var user = await User.findByEmail(email)

if (user != undefined) {
    var result = await bcrypt.compare(password, user.password)
    if (result) {
        var token = jwt.sign({email: user.email, role: user.role}, secret)
        res.status(200)
        res.json({token: token})
    } else {
        res.status(406)
fork icon0
star icon1
watch icon1

7
8
9
10
11
12
13
14
15
16
17
const User = require('./../models/userModel');
const catchAsync = require('./../utils/catchAsync');
const AppError = require('./../utils/appError');


const signToken = (id) => {
	return jwt.sign({ id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_TIMEOUT });
}
const createSendToken = (user, statusCode, res) => {
	const token = signToken(user.id);

fork icon1
star icon0
watch icon1

+ 5 other calls in file

85
86
87
88
89
90
91
92
93
94
    message:"Invalid passoword",

  })
}

 const token=await jwt.sign({_id:user._id},process.env.JWT_SECRET,{
  expiresIn:'7d',
 })
 res.status(200).send({
  success:true,
fork icon0
star icon0
watch icon1

34
35
36
37
38
39
40
41
42
43
        code: '403',
        message: 'Password Is Incorrect'
    })
} 

const token = jwt.sign(
    {
        id: user._id,
        username
    },
fork icon0
star icon0
watch icon1

+ 2 other calls in file

40
41
42
43
44
45
46
47
48
49
    if(!isMatch){
        return res
        .status(200)
        .send({message: 'Password is incorrect', success: false})
    } else{
        const token = jwt.sign({id: user._id}, process.env.JWT_SECRET, {expiresIn: '1d'})
        res.status(200).send({message: 'Login Successful', success: true, data:token})
    }
} catch (error){
    console.log(error);
fork icon0
star icon0
watch icon1

+ 2 other calls in file

4
5
6
7
8
9
10
11
12
13
14
const catchAsync = require('./../utils/catchAsync');
const AppError = require('./../utils/appError');
const sendEmail = require('./../utils/email');


const signToken = id => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN
  });
};

fork icon0
star icon0
watch icon1

294
295
296
297
298
299
300
301
302
303
  
      const userForToken = {
        username: user.username,
        id: user._id,
      }
      return { value: jwt.sign(userForToken, process.env.JWT_SECRET) }
    },
  }
}

fork icon0
star icon0
watch icon1

139
140
141
142
143
144
145
146
147
148
149
150


function generateRandomIdentifier() {
  let randomNumber = Math.floor(Math.random() * 100000);


  //generate jwt for the randomIdentifier
  jwtisedRandomNumber = jwt.sign(
    { randomNumber },
    "TOP_SECRET",
    { expiresIn: 5 * 24 * 60 * 60 } //5days
  );
fork icon0
star icon0
watch icon1

+ 2 other calls in file

10
11
12
13
14
15
16
17
18
19
const { email, password } = req.body;
const user = await User.findOne({ email });
if (user) {
	return res.json({ error: "Email is already taken" });
}
const token = jwt.sign({ email, password }, process.env.JWT_SECRET, { expiresIn: "1h" });
AWSSES.sendEmail(
	emailTemplate(email, ` <a href= "${CLIENT_URL}/api/v1/auth/account-activate/${token}">   Activate  account  </a>`, REPLY_TO, "Activate account"),

	(err, data) => {
fork icon0
star icon0
watch icon1

+ 2 other calls in file

111
112
113
114
115
116
117
118
119
120
function (err, admin, fields) {
    if (err) { res.json({ status: 'error', message: err }); return }
    if (admin.length == 0) { res.json({ status: 'error', message: 'no user found' }); return }
    bcrypt.compare(req.body.password, admin[0].password, function (err, isLogin) {
        if (isLogin) {
            var token = jwt.sign({ email: admin[0].email }, secret);
            res.json({ status: "ok", message: 'login success', token })
        } else {
            res.json({ status: "error", message: 'login fail' })
        }
fork icon0
star icon0
watch icon1

+ 2 other calls in file

79
80
81
82
83
84
85
86
87
88
    email : findData.email,
    id : findData.id,
    role : findData.role
}
if(match){
    const token = jwt.sign(pay_load, key)
    res.status(200).json({
        message : 'LOGGED IN SUCCESSFULLY',
        'token' : token
    })
fork icon0
star icon0
watch icon1

+ 2 other calls in file

347
348
349
350
351
352
353
354
355
356

    log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`);

    callback({
        ok: true,
        token: jwt.sign({
            username: data.username,
        }, jwtSecret),
    });
}
fork icon0
star icon0
watch icon1

+ 5 other calls in file