Resolving redirect issues with Slim 4 authentication middleware
P粉949848849
P粉949848849 2023-08-13 12:04:52
0
1
595
<p>我正在尝试使用中间件将未经身份验证的用户重定向到Google API身份验证。 如果我直接访问身份验证系统(通过访问/auth路由),Google部分可以工作,并且用户会被发送到我的主页。但是,如果我访问受中间件保护的页面,我会得到一个空白页面。</p><p> 这是我的中间件:</p> <pre class="brush:php;toolbar:false;"><?php declare(strict_types=1); namespace AppMiddleware; use SlimPsr7Response; use PsrHttpMessageServerRequestInterface as Request; use PsrHttpServerRequestHandlerInterface as RequestHandler; class Auth { public function __invoke(Request $request, RequestHandler $handler): Response { if (!isset($_SESSION['access_token'])) { $response = new Response(); $response->withHeader('Location', '/auth')->withStatus(302); } else { $response = $handler->handle($request); } return $response; } }</pre> <p>由于Google部分可以工作,问题肯定在我的中间件中,对吗?这也意味着中间件的else部分是起作用的。 有什么建议吗?</p><p> TIA</p>
P粉949848849
P粉949848849

reply all(1)
P粉278379495

It turns out that it’s because I didn’t drink enough coffee when I wrote this code. I forgot to set the mutated response to a variable.
Inside my if statement it should be:

$response = new Response();                                                                                                                                                                                                                    
        $response = $response->withHeader('Location', '/auth')->withStatus(302);

The "$response =" in the second line is the part I missed.
Hope this helps others.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template