如何将变量传递给RedirectResponse?以$email传递至dashController为例
如何将认证后的$email传递到dashController的模板中?
以下是几种可行的实现方案,你可以根据自身场景选择:
方案一:从JWT令牌中解析Email(推荐)
既然你已经将JWT令牌存入Cookie,通常JWT的Payload中会包含用户邮箱这类基础信息,直接解析令牌就能获取,无需额外存储:
修改dashController.php的indexAction方法:
class dashController extends authContainer { #[Route("/dash", "dashboard")] public function indexAction(): Response { // 获取Cookie中的JWT令牌 $jwtToken = $this->request->cookies->get('JWT'); // 解析JWT(示例使用firebase/php-jwt库,需根据你实际使用的JWT工具调整) $decoded = \Firebase\JWT\JWT::decode( $jwtToken, new \Firebase\JWT\Key('你的JWT密钥', 'HS256') // 替换为你实际的加密算法和密钥 ); // 从解析后的Payload中提取email $email = $decoded->email; return $this->render('dash.twig', [ 'email' => $email ]); }}
注意:需要确保生成JWT时,已将
方案二:额外将Email存入Cookie
如果JWT中未包含邮箱,或不想解析令牌,可以在认证成功时把邮箱存入独立Cookie:
修改认证逻辑代码:
$action = $this->client->auth($username, $password); if (isset($action->success) && $action->success){ $email = $action->data->email; $response = new RedirectResponse('/dash'); $cookie = new Cookie('JWT', $action->data->jwt->token, new \DateTime($action->data->jwt->expires_at)); // 添加存储邮箱的Cookie,过期时间与JWT保持一致 $emailCookie = new Cookie('user_email', $email, new \DateTime($action->data->jwt->expires_at)); $response->headers->setCookie($cookie); $response->headers->setCookie($emailCookie); return $response; }
然后在dashController中获取:
class dashController extends authContainer { #[Route("/dash", "dashboard")] public function indexAction(): Response { $email = $this->request->cookies->get('user_email'); return $this->render('dash.twig', [ 'email' => $email ]); }}
注意:Cookie存储为明文,若邮箱属于敏感信息,不建议使用此方案。
方案三:使用Session存储Email
如果你的应用已配置Session,可以将邮箱存入Session中:
修改认证逻辑代码:
$action = $this->client->auth($username, $password); if (isset($action->success) && $action->success){ $email = $action->data->email; // 将邮箱存入Session $this->session->set('user_email', $email); $response = new RedirectResponse('/dash'); $cookie = new Cookie('JWT', $action->data->jwt->token, new \DateTime($action->data->jwt->expires_at)); $response->headers->setCookie($cookie); return $response; }
然后在dashController中获取:
class dashController extends authContainer { #[Route("/dash", "dashboard")] public function indexAction(): Response { $email = $this->session->get('user_email'); return $this->render('dash.twig', [ 'email' => $email ]); }}
内容的提问来源于stack exchange,提问作者egos
相关产品推荐
相关产品推荐

