2015-08-08 57 views

回答

5

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

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

然后,您可以在成功登录时使用此选项重定向到所需的页面。这里有一个可运行的例子,你可以玩,并修改您的需要:在浏览器中

  • 导航到http://localhost:8080/greetings
  • 你会被重定向到/login
  • 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!'); 
    }); 
    

    为了验证这一点,

  • 点击登录按钮
  • 将帖子发送到/login,然后重定向到/greetings成功
相关问题