OTP generation in nodejs using speakeasy :set expiry time

6k Views Asked by At

I am using https://www.npmjs.com/package/speakeasy to generate OTP and i would like the expiry to 10 minutes.

Here is the code for generation

const generateOtp = function generateOtp() {
    let token = speakeasy.totp({
        secret:process.env.OTP_KEY,
        encoding: 'base32',
        digits:4,
        window:10
    });
    return token;
}

Verify OTP

const verifyOtp = function verifyOtp(token){
    let expiry =  speakeasy.totp.verify({
        secret:process.env.OTP_KEY,
        encoding: 'base32',
        token: token,
        window:10
    });
    console.log(expiry)
}

But I don't know how to set the expiry to 10 minutes??

2

There are 2 best solutions below

0
On

In order to expire the token after a while , you need to use the step option of speakeasy package like this :

speakeasy.time({
    encoding: "base32",
    secret: "secret",
    digits: 4,
    step: 600, // expire after 10 minutes
});

speakeasy.time.verify({
    token: "1234",
    secret: "secret",
    encoding: "base32",
    digits: 4,
    step: 600, // expire after 10 minutes
});

Just make sure that the options you provide for generating token are the same as verify.

1
On

Reading the documentation you can find out that the base step is 30 seconds, so if you want to have an expiration time of 10 minutes you need to set up the step to 60. Then, using the verifyDelta method you should be able to check if the token expired.

const generateOtp = function generateOtp() {
    let token = speakeasy.totp({
        secret:process.env.OTP_KEY,
        encoding: 'base32',
        digits:4,
        step: 60,
        window:10
    });
    return token;
}

const verifyOtp = function verifyOtp(token){
    let expiry =  speakeasy.totp.verifyDelta({
        secret:process.env.OTP_KEY,
        encoding: 'base32',
        token: token,
        step: 60,
        window:10
    });
    console.log(expiry)
}