简体   繁体   English

错误后如何重定向PassportJS / Express内?

[英]How to redirect after error inside of PassportJS/Express?

When configuring passport using Express and NodeJS, I am throwing an error if the user has an invalid email address. 使用Express和NodeJS配置通行证时,如果用户的电子邮件地址无效,则会引发错误。 After this error I would like to redirect to a failure page giving them instructions on how to log in correctly. 发生此错误后,我想重定向到失败页面,为他们提供有关如何正确登录的说明。 Is there are a better way to do this? 有没有更好的方法可以做到这一点? If not, how would I go about catching the error in some fashion and redirecting to a new page. 如果没有,我将如何以某种方式捕获错误并重定向到新页面。

passport.use(new GoogleStrategy({
        clientID     : auth.googleAuth.clientID,
        /* Settings redacted for brevity */
    },
    function(token, refreshToken, profile, done) {
        User.findOne(
            {
                "google.id" : profile.id
            },
            function(err, user) {

                if (err) return done(err)

                if (user) return done(null, user)

                else {

                    if (email.indexOf("lsmsa.edu") > -1) {

                        // Code redacted for brevity

                    } else {
                        done(new Error("Invalid email address"))
                    }
                }
            }
        )
    }))

Note: I quite like BlackMamba's answer as well, adding the custom callback / redirect is a perfectly acceptable option. 注意:我也非常喜欢BlackMamba的答案,添加自定义回调/重定向是一个完全可以接受的选项。

Simply add your own error handling middleware to Express: 只需将您自己的错误处理中间件添加到Express中:

passport.use(new GoogleStrategy({
    clientID     : auth.googleAuth.clientID,
    /* Settings redacted for brevity */
},
function(token, refreshToken, profile, done) {
    User.findOne({
            "google.id" : profile.id
        },
        function(err, user) {

            if (err) return done(err)

            if (user) return done(null, user)

            else {

                if (email.indexOf("lsmsa.edu") > -1) {

                } else {
                    // Throw a new error with identifier:
                    done(throw {
                        type: "invalid_email_address", 
                        code: 401, 
                        profileId: profile.id
                    }));
                }
            }
        }
    )
}));

// The error handling middleware:

app.use(function(e, req, res, next) {
    if (e.type === "invalid_email_address") {
        res.status(e.code).json({
            error: {
                msg: "Unauthorized access", 
                user: e.profileId
            }
        });
    }
});

You'll notice I modified this answer a little bit with a more robust error composition. 您会注意到我用更健壮的错误组成对这个答案进行了一点修改。 I've defined the code property of the error to match the applicable HTTP status code -- in this case, 401 : 我已经定义了错误的code属性以匹配适用的HTTP状态代码-在这种情况下为401

// callback
done(throw {
    // just a custom object with whatever properties you want/need
    type: "invalid_email_address",
    code: 401, 
    profileId: profile.id
}));

In the error handling, we simply check the type is invalid_email_address (you can make it whatever you want, but it should be consistent across your app) and then write the error out using the "code" as the HTTP status code: 在错误处理中,我们只需检查类型为invalid_email_address (您可以根据需要进行设置,但在整个应用程序中应保持一致),然后使用“代码”作为HTTP状态代码将错误写出:

          // e is the error object, and code is the custom property we defined
res.status(e.code).json({
    error: {
        msg: "Unauthorized access",
        user: e.profileId
    }
});

Here's a self-contained working example with a redirect: 这是一个带有重定向的独立工作示例:

var express = require('express');
var app = express();

app.all('*', function(req, res) {
    throw {type: "unauthorized", code: 401}
})

app.use(function(e, req, res, next) {
    console.log(e);
    if (e.code === 401) {
        res.redirect("/login")
    } else {
        res.status(500).json({error: e.type});
    }
});

app.listen(9000);

I think you can use this: 我认为您可以使用此:

Redirects 重新导向

A redirect is commonly issued after authenticating a request. 重定向通常是在验证请求后发出的。

app.post('/login',
  passport.authenticate('local', { successRedirect: '/',
                                   failureRedirect: '/login' }));

In this case, the redirect options override the default behavior. 在这种情况下,重定向选项将覆盖默认行为。 Upon successful authentication, the user will be redirected to the home page. 身份验证成功后,用户将被重定向到主页。 If authentication fails, the user will be redirected back to the login page for another attempt. 如果身份验证失败,用户将被重定向回登录页面以进行另一次尝试。

Or this: 或这个:

Custom Callback 自定义回调

If the built-in options are not sufficient for handling an authentication request, a custom callback can be provided to allow the application to handle success or failure. 如果内置选项不足以处理身份验证请求,则可以提供自定义回调以允许应用程序处理成功或失败。

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

Please read the document: http://passportjs.org/docs/authenticate 请阅读文档: http : //passportjs.org/docs/authenticate

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

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