如何解决Symfony/Api platorm/JWT 登录后获取当前用户
大家早上好 请我需要帮助。我正在使用 JWT 身份验证并且一切正常。但我的问题是在登录后检索当前用户。我在文档中看到我可以创建一个控制器来这样做,但是在这样做之后我得到了没有给出 id 参数的错误。 这是我与用户实体相关的控制器
// api/src/Controller/GetMeAction.PHP
namespace App\Controller;
use App\Entity\User;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
class GetMeAction
{
/**
* @param Security
*/
private $_security;
public function __construct(Security $security)
{
$this->_security = $security;
}
/**
* @Route(
* name="get_me",* path="get/me",* methods={"GET"},* defaults={
* "_api_resource_class"=User::class,* "_api_item_operation_name"="get_me"
* }
* )
*/
public function __invoke(Request $request): User
{
return $this->_security->getUser();
}
}
解决方法
先前的答案是正确的,但您忘记从抽象的一个扩展控制器:
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class AdminController extends AbstractController
{
}
如果你想在服务中获取 User,你可以在你的 __construct() 中注入 Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface
你可以让用户喜欢:
public function getUser(): ?User
{
$token = $this->tokenStorage->getToken();
if (!$token) {
return null;
}
$user = $token->getUser();
if (!$user instanceof User) {
return null;
}
return $user;
}
,
我使用的是 symfony 5.3,我想使用 api 平台规范化和项目操作“get”来保留所有自定义配置、安全性、服务……
所以我在控制器中使用了 forward()
方法:
/**
* @Route("/api/user/me",name="get_me")
*/
public function getMe(): Response
{
$router = $this->get('router')->getRouteCollection()->get('api_users_get_item');
$defaults = $router->getDefaults();
return $this->forward($router->getDefault('_controller'),array_merge($defaults,[ 'id' => $this->getUser()->getId()]));
}
,
在您的控制器中,您不需要 $_security 您可以使用 $this->getUser()
直接访问当前用户版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。