javascript 在验证架构中使用isStrongPassword

lndjwyie  于 2023-06-20  发布在  Java
关注(0)|答案(2)|浏览(97)

我尝试使用express-validator定义一个模式,其中设置了“isStrongPassword”选项。“usernameSchema”工作正常,但“passwordSchema”不能通过我输入的密码,即使它们符合要求。
下面是我的代码:
userRouter.js

const { usernameSchema, passwordSchema } = require("../services/validationSchemas");

router.post("/register", checkSchema({ username: usernameSchema, password: passwordSchema }), (req, res) => {
  const result = validationResult(req);
  if (result.isEmpty()) {
    res.json({
      username: req.query.username,
      password: req.query.password
    });
  } else {
    res.send({
      errors: result.array()
    });
  }
});

validationSchemas.js

const usernameSchema = {...};

const passwordSchema = {
  errorMessage: "Enter a valid password.",
  trim: true,
  notEmpty: {
    bail: true
  },
  isStrongPassword: {
    minLength: 8,
    minLowercase: 1,
    minUppercase: 1,
    minNumbers: 1
  },
  errorMessage: "Password doesn't match the requirements."
};

module.exports = {
  usernameSchema: usernameSchema,
  passwordSchema: passwordSchema
};

即使我输入了符合要求的密码,也会出现以下错误:

{
    "errors": [
        {
            "type": "field",
            "value": "124sdjAfsd",
            "msg": "Password doesn't match the requirements.",
            "path": "password",
            "location": "query"
        }
    ]
}

有人能帮我吗?

pkwftd7m

pkwftd7m1#

现在做了一些测试(版本7.0.1)
Express验证器使用默认值,除非你覆盖它们,你没有通过,因为你没有覆盖minSymbols,所以它需要1个特殊的字符。
但是如果你使用schema,有一个bug,你不能覆盖默认值(8个字符,1个小写,1个大写,1个数字和1个特殊),
我可以通过这个密码:aA1@1245即使有这个疯狂的配置:

const passwordSchema = {
    trim: true,
    notEmpty: {
        bail: true
    },
    isStrongPassword: {
        minLength: 1000000000,
        minLowercase: 1000000000,
        minUppercase: 1000000000,
        minNumbers: 1000000000,
        minSymbols: 1000000000
    },
    errorMessage: "Gotta be kidding"
};

为了能够实现你想要的(覆盖minSymbol),你必须使用链验证:

const passwordConfig = {
    minLength: 8,
    minLowercase: 1,
    minUppercase: 1,
    minNumbers: 1,
    minSymbols: 0 //🟥 dont require special chars
}

router.post("/register",
    checkSchema({ username: usernameSchema }), //🟥 first middleware - schema validation
    query('password').isStrongPassword(passwordConfig), //🟥 second middleware - chain validation
    (req, res) => {
        const result = validationResult(req);
        if (result.isEmpty()) {
            res.json({
                username: req.query.username,
                password: req.query.password
            });
        } else {
            res.send({
                errors: result.array()
            });
        }
    });
guicsvcw

guicsvcw2#

使用模式验证时,需要在验证器的options属性下传递选项。如果你直接将它们传递给验证器,它们将不起作用。

isStrongPassword: {
  options: {
    minLength: 8,
    minLowercase: 1,
    minUppercase: 1,
    minNumbers: 1
  }
}

文档

相关问题