Slim 3中间件重定向 [英] Slim 3 Middleware Redirect
问题描述
我想检查用户是否已登录.因此,我有一个Class witch返回true或false.现在,我需要一个可检查用户是否已登录的中间件.
I want to check if a user is logged in. Therefor I have an Class witch returns true or false. Now I want a middleware which checks if the user is logged in.
$app->get('/login', '\Controller\AccountController:loginGet')->add(Auth::class)->setName('login');
$app->post('/login', '\Controller\AccountController:loginPost')->add(Auth::class);
身份验证类
class Auth {
protected $ci;
private $account;
//Constructor
public function __construct(ContainerInterface $ci) {
$this->ci = $ci;
$this->account = new \Account($this->ci);
}
public function __invoke($request, \Slim\Http\Response $response, $next) {
if($this->account->login_check()) {
$response = $next($request, $response);
return $response;
} else {
//Redirect to Homepage
}
}
}
因此,当用户登录时,页面将正确呈现.但是,当不强制用户时,我想重定向到主页.但是如何?!
So when the user is logged in the page will render correctly. But when the user is not autoriesed I want to redirect to the homepage. But how?!
$response->withRedirect($router->pathFor('home');
这不起作用!
推荐答案
您需要return
响应.不要忘记request
和response
对象是不可变的.
You need to return
the response. Don't forget that the request
and response
objects are immutable.
return $response = $response->withRedirect(...);
我有一个类似的身份验证中间件,这就是我做的方法,它还添加了403(未授权)标头.
I have a similar auth middleware and this is how I do it which also adds a 403 (unauthorized) header.
$uri = $request->getUri()->withPath($this->router->pathFor('home'));
return $response = $response->withRedirect($uri, 403);
这篇关于Slim 3中间件重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!