简体   繁体   中英

AuthenticationException even though i got the appropriate user

this question is next part of this one: doctrine getRepository errors

After few fixes and help from Dylan, ive managed to get from this piece of code

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        try {
            $credentials = str_replace('Bearer ', '', $credentials);
            $jwt = (array) JWT::decode(
                $credentials,
                $this->params->get('jwt_secret'),
                ['HS256']
            );
            dump($jwt['user']);
            dump($this->em
                ->getRepository(User::class)//TODO Fix here
                ->findOneBy(['email' => $jwt['email']]));
            return $this->em
                ->getRepository(User::class)//TODO Fix here
                ->findOneBy(['username' => $jwt['user']]);
        }catch (\Exception $exception) {
            throw new AuthenticationException($exception->getMessage());

        }
    }

after dumping jwt['user'] and whole return i got this:

Return from postman

as you can see i got both of dumps valid yet still i got error xd. Any clues/ideas why?

Edit 1: security.yaml:

security:
    encoders:
        App\Entity\User: bcrypt
    enable_authenticator_manager: true
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern: ^/api
            stateless: true
            provider: app_user_provider
            guard:
                authenticators:
                    - App\Security\JwtAuthenticator

Edit2 JwtAuthenticator.php:

namespace App\Security;
use App\Entity\User;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Firebase\JWT\JWT;
use Symfony\Component\HttpFoundation\JsonResponse;

class JwtAuthenticator extends AbstractGuardAuthenticator
{
    private $em;
    private $params;

    public function __construct(EntityManagerInterface $em, ContainerBagInterface $params)
    {
        $this->em = $em;
        $this->params = $params;
    }

    public function supports(Request $request)
    {
        return $request->headers->has('Authorization');
    }

    public function getCredentials(Request $request)
    {
        return $request->headers->get('Authorization');
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        try {
            $credentials = str_replace('Bearer ', '', $credentials);
            $jwt = (array) JWT::decode(
                $credentials,
                $this->params->get('jwt_secret'),
                ['HS256']
            );


            dump($jwt['user']);
            dump($this->em
                ->getRepository(User::class)
                ->findOneBy(['email' => $jwt['email']]));


            return $this->em
                ->getRepository(User::class)
                ->findOneBy(['username' => $jwt['user']]);
        }catch (\Exception $exception) {
            throw new AuthenticationException($exception->getMessage());

        }
    }

    public function checkCredentials($credentials, UserInterface $user)
    {

    }


    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        return new JsonResponse([
            'message' => $exception->getMessage()
        ], Response::HTTP_UNAUTHORIZED);
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey)
    {
        return; 
    }

    public function supportsRememberMe()
    {
        return false;
    }

    public function start(Request $request, AuthenticationException $authException = null)
    {
        $data = [
            'message' => 'Authentication Required'
        ];
        return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
    }
}

The error seems to be easy to understand.

CheckCredentials is supposed to return true for the connection to be valid.

You may need to check if $user is found. But I believe just writing return true would work since an exception would be thrown before if user was not found.

For example:

public function checkCredentials($credentials, UserInterface $user)
    {
         if ($user instanceof User){
             return true;
         }
         return false;
    }

Something similar is done here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM