简体   繁体   English

Node.js Web 应用:Passport.js failureRedirect display message in ejs

[英]Node.js Web Application: Passport.js failureRedirect display message in ejs

I am using Passport.js to authenticate user login.我正在使用 Passport.js 来验证用户登录。 This is my code at the moment:这是我目前的代码:

app.post('/login', passport.authenticate('local', {
  failureRedirect: '/login',
  successRedirect: "/secrets",
  failureMessage: "Incorrect password"
}));

Basically, if authentication succeeds it will direct to the "secrets" page;基本上,如果身份验证成功,它将直接进入“秘密”页面; if authentication fails it will redirect back to "login" page.如果身份验证失败,它将重定向回“登录”页面。

The authentication works well in this case;在这种情况下,身份验证效果很好; however, when the authentication fails and it redirects back to the login page, I also want the failureMessage to display in a ejs template I have for the login page.但是,当身份验证失败并重定向回登录页面时,我还希望 failureMessage 显示在登录页面的 ejs 模板中。 How can I do that?我怎样才能做到这一点?

I want something like this in ejs (but this code does not work, of course):我在 ejs 中想要这样的东西(但这段代码当然不起作用):

<a> <%= failureMessage %> </a>

Including failureMessage: 'message' as you have done above adds your message to the session, which can then be accessed via the request object in the route handler, assuming you have session authentication set up.包括 failureMessage: 'message' 如上所述,将您的消息添加到 session,然后可以通过路由处理程序中的请求 object 访问,假设您有 Z21D6F40CFB511982E4524E0E250 设置身份验证。 In the route handler for GET requests to /login (where you are redirecting to in the event of authentication failure) you can pass the messages array on the session to your ejs template:在对 /login 的 GET 请求的路由处理程序中(在身份验证失败的情况下您将重定向到该位置),您可以将 session 上的消息数组传递给您的 ejs 模板:

app.get('/login', (req, res) => {res.render('login', {messages: req.session.messages})});

You can then access messages in the login.ejs template with something like this:然后,您可以使用以下内容访问 login.ejs 模板中的消息:

<a> <%= messages[0] %> </a>

From the docs: This (the failureRedirect option) is often paired with the failureMessage option, which will add an informative message to the session about why authentication failed which can then be displayed to the user.来自文档:这(failureRedirect 选项)通常与 failureMessage 选项配对,它将向 session 添加一条信息性消息,说明身份验证失败的原因,然后可以显示给用户。 https://www.passportjs.org/concepts/authentication/ https://www.passportjs.org/concepts/authentication/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM