Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Symfony 在令牌存储中找不到令牌_Symfony - Fatal编程技术网

Symfony 在令牌存储中找不到令牌

Symfony 在令牌存储中找不到令牌,symfony,Symfony,因此,我正在使用Guard验证器对用户进行身份验证 登录和注销成功,但当我尝试在其他路由上请求时,它抛出AuthenticationCredentialsNotFoundException 在令牌存储中找不到令牌 因此,以401作为回应 这是我的验证器类: class ApiAuthenticator extends AbstractGuardAuthenticator implements LogoutSuccessHandlerInterface { public f

因此,我正在使用Guard验证器对用户进行身份验证

登录和注销成功,但当我尝试在其他路由上请求时,它抛出AuthenticationCredentialsNotFoundException

在令牌存储中找不到令牌

因此,以401作为回应

这是我的验证器类:

class ApiAuthenticator extends AbstractGuardAuthenticator implements LogoutSuccessHandlerInterface
    {
        public function getCredentials(Request $request)
        {
            if ($request->getPathInfo() != '/login' || !$request->isMethod('POST')) {
                return;
            }

            $data = json_decode($request->getContent(), true);

            return [
                'username' => $data['_username'],
                'password' => $data['_password'],
            ];
        }

        public function getUser($credentials, UserProviderInterface $userProvider)
        {
            return $userProvider->loadUserByUsername($credentials);
        }

        public function checkCredentials($credentials, UserInterface $user)
        {
            if (!$user instanceof User) {
                throw new \TypeError();
            }

            return true;
        }

        public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
        {
            return new JsonResponse([ 'error' => 'Invalid Credentials!'], Response::HTTP_UNAUTHORIZED);    }

        public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
        {
            $response = [
                'success' => 'Success!',
                'customer' => [
                    'name' => 'Fullname',
                    'memberSince' => 'mm/dd/yyyy'

                ]
            ];

            return new JsonResponse($response, Response::HTTP_OK);
        }

        public function start(Request $request, AuthenticationException $authException = null)
        {   
            return new Response('', Response::HTTP_UNAUTHORIZED);
        }

        public function supportsRememberMe()
        {

        }

        public function onLogoutSuccess(Request $request)
        {
            $request->getSession()->invalidate();
            return new Response();
        }
    }
这是我的UserProvider类:

class UserProvider implements UserProviderInterface
{
    private $apiHelper;
    private $session;

    public function __construct(ApiHelper $apiHelper, Session $session)
    {
        $this->apiHelper = $apiHelper;
        $this->session = $session;
    }

    public function loadUserByUsername($credentials)
    {
        $response = $this->apiHelper->generateAccessToken($credentials['username'], $credentials['password']);

        if (isset($response['access_token'])) {

            $this->session->set('authAccessToken', $response['access_token']);
            $this->session->set('authExpiresIn', $response['expires_in']);
            $this->session->set('authRefreshToken', $response['refresh_token']);

            $accessToken = new AccessToken();
            $accessToken->setAccessToken($response['access_token']);
            $accessToken->setExpiresIn($response['expires_in']);
            $accessToken->setTokenType($response['token_type']);
            $accessToken->setScope($response['scope']);
            $accessToken->setRefreshToken($response['refresh_token']);

            return new User($accessToken);
         }

         throw new UsernameNotFoundException(
            sprintf('Username "%s" does not exist.', '')
        );
    }

    public function refreshUser(UserInterface $user)
    {
        if (!$user instanceof User) {
            throw new UnsupportedUserException(
                sprintf('Instances of "%s" are not supported.', get_class($user))
            );
        }

        return $user;

            // return $this->loadUserByUsername([
            //     'password' => $user->getPassword(),
            //     'username' => $user->getUsername(),
            // ]);
    }

    public function supportsClass($class)
    {
        return User::class === $class;
    }
}
这是我的安全

security:
    providers:
        user_provider:
            id: user_provider

    firewalls:
        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            http_basic: ~
            pattern: ^/
            provider: user_provider
            logout:
                path:   /logout
                success_handler: api_authenticator
            guard:
                authenticators:
                    - api_authenticator
    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/test, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, roles: IS_AUTHENTICATED_FULLY }

谢谢

尝试实现
AuthenticationFailureHandlerInterface
并在
onAuthenticationFailure
中引发异常尝试实现
AuthenticationFailureHandlerInterface
并在
onAuthenticationFailure
中引发异常

main:
    # ...
    anonymous: true
    # ...
yml将有助于将该异常转换为AccessDeniedException(在开发模式下通常应转换为UnficientAuthenticationException,并在prod模式下使用内核异常侦听器重定向到登录,但这取决于您)。

添加

main:
    # ...
    anonymous: true
    # ...

security.yml将有助于将该异常转换为AccessDeniedException(在开发模式下通常应转换为UnficientAuthenticationException,并在prod模式下重定向到使用内核异常侦听器登录,但这取决于您)。

显然,我只是在refresshUser()中返回$user,它就可以工作了。我不太确定whay:)显然,我只是在refresshUser()中返回$user,它就工作了。我真的不太确定(whiy:)