【问题标题】:hapi.js - How to redirect to originally requested route after successful authentication?hapi.js - 成功认证后如何重定向到最初请求的路由?
【发布时间】:2015-08-08 18:40:01
【问题描述】:

hapi.js 中有类似reply.redirect('back') 的东西吗?我正在尝试将用户重定向回他们成功登录之前请求的原始页面。

【问题讨论】:

    标签: node.js authentication hapijs


    【解决方案1】:

    使用hapi-auth-cookie 方案时,有一个方便的设置可用于此目的。看看appendNext in the options

    当您将此设置为true 时,重定向到您的登录页面将包含一个查询参数nextnext等于原始请求的请求路径

    然后,您可以在成功登录时使用它来重定向到所需的页面。这是一个可运行的示例,您可以根据需要进行修改和修改:

    var Hapi = require('hapi');
    
    var server = new Hapi.Server();
    server.connection({ port: 8080 });
    
    server.register(require('hapi-auth-cookie'), function (err) {
    
        server.auth.strategy('session', 'cookie', {
            password: 'secret',
            cookie: 'sid-example',
            redirectTo: '/login',
            appendNext: true,      // adds a `next` query value
            isSecure: false
        });
    });
    
    server.route([
        {
            method: 'GET',
            path: '/greetings',
            config: {
                auth: 'session',
                handler: function (request, reply) {
    
                    reply('Hello there ' + request.auth.credentials.name);
                }
            }
        },
        {
            method: ['GET', 'POST'],
            path: '/login',
            config: {
                handler: function (request, reply) {
    
                    if (request.method === 'post') {
                        request.auth.session.set({
                            name: 'John Doe'    // for example just let anyone authenticate
                        });
    
                        return reply.redirect(request.query.next); // perform redirect
                    }
    
                    reply('<html><head><title>Login page</title></head><body>' + 
                          '<form method="post"><input type="submit" value="login" /></form>' +
                          '</body></html>');
                },
                auth: {
                    mode: 'try',
                    strategy: 'session'
                },
                plugins: {
                    'hapi-auth-cookie': {
                        redirectTo: false
                    }
                }
            }
        }
    ]);
    
    server.start(function (err) {
    
        if (err) {
            throw err;
        }
    
        console.log('Server started!');
    });
    

    测试一下:

    • 在浏览器中导航到http://localhost:8080/greetings
    • 您将被重定向到/login
    • 点击登录按钮
    • 将帖子发送到/login,然后在成功时重定向到/greetings

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-18
      • 2019-02-20
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 2020-07-01
      • 2022-09-23
      相关资源
      最近更新 更多