GaxiosError: invalid_grant in my nodejs app when i want to verify register user email

GaxiosError: invalid_grant in my nodejs app when i want to verify register user email

当用户在我的 nodejs 后端应用程序中注册时,我想验证用户电子邮件我正在使用 auth2.0 我正在提供客户端 ID、密码但响应给我错误

(GaxiosError: invalid_grant at Gaxios._request (/home/amir/Desktop/Nodejs/Auth/backend/node_modules/gaxios/build/src/gaxios.js:84:23) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async OAuth2Client.refreshTokenNoCache (/home/amir/Desktop/Nodejs/Auth/backend/node_modules/google-auth-library/build/src/auth/oauth2client.js:172:21) at async OAuth2Client.refreshAccessTokenAsync (/home/amir/Desktop/Nodejs/Auth/backend/node_modules/google-auth-library/build/src/auth/oauth2client.js:196:19) at async OAuth2Client.getAccessTokenAsync (/home/amir/Desktop/Nodejs/Auth/backend/node_modules/google-auth-library/build/src/auth/oauth2client.js:216:23) )

我也给了 refresh_token 但它不起作用我不知道我哪里做错了请任何人解决它

这是我的代码或 api 用于注册用户的代码

exports.registerHandle = (req, res) => {
const { name, email, password, password2 } = req.body;
let errors = [];

//------------ Checking required fields ------------//
if (!name || !email || !password || !password2) {
    errors.push({ msg: 'Please enter all fields' });
}

//------------ Checking password mismatch ------------//
if (password != password2) {
    errors.push({ msg: 'Passwords do not match' });
}

//------------ Checking password length ------------//
if (password.length < 8) {
    errors.push({ msg: 'Password must be at least 8 characters' });
}

if (errors.length > 0) {
    res.render('register', {
        errors,
        name,
        email,
        password,
        password2
    });
} else {
    //------------ Validation passed ------------//
    User.findOne({ email: email }).then(user => {
        if (user) {
            //------------ User already exists ------------//
            errors.push({ msg: 'Email ID already registered' });
            res.render('register', {
                errors,
                name,
                email,
                password,
                password2
            });
        } else {

            const oauth2Client = new OAuth2(
                "My ID", // ClientID
                "MY Secret", // Client Secret
                "https://developers.google.com/oauthplayground" // Redirect URL
            );

            oauth2Client.setCredentials({
                refresh_token: "1%2F%2F04T_nqlj9UVrVCgYIARAAGAQSNwF-L9IrGm-NOdEKBOakzMn1cbbCHgg2ivkad3Q_hMyBkSQen0b5ABfR8kPR18aOoqhRrSlPm9w"
            });
            const accessToken = oauth2Client.getAccessToken()
            console.log('Google Access Token ===', accessToken);

            const token = jwt.sign({ name, email, password }, JWT_KEY, { expiresIn: '30m' });
            console.log('Token ', token);
            const CLIENT_URL = 'http://' + req.headers.host;

            const output = `
            <h2>Please click on below link to activate your account</h2>
            <p>${CLIENT_URL}/auth/activate/${token}</p>
            <p><b>NOTE: </b> The above activation link expires in 30 minutes.</p>
            `;

            const transporter = nodemailer.createTransport({
                service: 'gmail',
                auth: {
                    type: "OAuth2",
                    user: "mygmail@gmail.com",
                    clientId: "My ID",
                    clientSecret: "My Secret",
                    refreshToken: "1%2F%2F04T_nqlj9UVrVCgYIARAAGAQSNwF-L9IrGm-NOdEKBOakzMn1cbbCHgg2ivkad3Q_hMyBkSQen0b5ABfR8kPR18aOoqhRrSlPm9w",
                    accessToken: accessToken
                },
            });

            // send mail with defined transport object
            const mailOptions = {
                from: '"Auth Admin" <mygmail@gmail.com>', // sender address
                to: email, // list of receivers
                subject: "Account Verification: NodeJS Auth ✔", // Subject line
                generateTextFromHTML: true,
                html: output, // html body
            };

            transporter.sendMail(mailOptions, (error, info) => {
                if (error) {
                    console.log(error);
                    req.flash(
                        'error_msg',
                        'Something went wrong on our end. Please register again.'
                    );
                    res.redirect('/auth/login');
                }
                else {
                    console.log('Mail sent : %s', info.response);
                    req.flash(
                        'success_msg',
                        'Activation link sent to email ID. Please activate to log in.'
                    );
                    res.redirect('/auth/login');
                }
            })

        }
    });
}
}

Invalid_grant 可能有很多原因。最常见的原因是刷新令牌过期。正在测试的应用在 7 天后会被撤销同意,这会导致刷新令牌过期。

您似乎正在从授权请求中加载当前访问令牌

const accessToken = oauth2Client.getAccessToken()

但您似乎也有一个硬编码的刷新令牌

refreshToken: "1%2F%2F04T_nqlj9UVrVCgYIARAAGAQSNwF-L9IrGm-NOdEKBOakzMn1cbbCHgg2ivkad3Q_hMyBkSQen0b5ABfR8kPR18aOoqhRrSlPm9w",

为什么不存储最新的刷新令牌呢?