简体   繁体   English

AuthenticationException 即使我得到了适当的用户

[英]AuthenticationException even though i got the appropriate user

this question is next part of this one: doctrine getRepository errors这个问题是这个问题的下一部分: doctrine getRepository errors

After few fixes and help from Dylan, ive managed to get from this piece of code在 Dylan 的几次修复和帮助之后,我设法从这段代码中得到了

    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:在倾销 jwt['user'] 和整个回报后,我得到了这个:

Return from postman从 postman 返回

as you can see i got both of dumps valid yet still i got error xd.如您所见,我的两个转储均有效,但仍然出现错误 xd。 Any clues/ideas why?任何线索/想法为什么?

Edit 1: security.yaml:编辑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: 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. CheckCredentials 应该返回 true 以使连接有效。

You may need to check if $user is found.您可能需要检查是否找到$user But I believe just writing return true would work since an exception would be thrown before if user was not found.但我相信只写return true会起作用,因为如果找不到用户,之前会抛出异常。

For example:例如:

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

Something similar is done here . 这里做了类似的事情

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的代码中已明确定义了未定义的变量,为什么呢? - why is it I got undefined variable even though it is clearly defined in my code? 即使URL具有适当的格式,也不会填充$ _GET参数 - $_GET parameter is not populated, even though URL has appropriate form 即使我自己创建了用户帐户PHPMyAdmin,也拒绝了用户访问 - Access denied for user even though I created the user account myself PHPMyAdmin 即使我创建了所需的用户,也无法从Laravel连接到MySQL数据库 - Can't connect to MySQL database from Laravel, even though I created the required user 即使我输入了有效的表和列,表单也没有收集用户输入并且查询无法正常工作 - The form is not collecting the user input and the query is not working properly even though I have typed in a valid table and column 尽管我定义了“ id”,但雄辩的口号一直在寻找“ user_id”而不是“ id” - Eloquent whereHas is looking for 'user_id' instead of 'id' even though I defined 'id' Symfony 守卫抛出 AuthenticationException 但用户加载成功 - Symfony guard throws AuthenticationException but user loaded successfully 即使用户有效,页面也不接受登录用户 - Page not accepting user on login even though user is valid 即使设置了路由也未定义 - Route not defined even though I set them 显示 @guest 标记内的元素,即使用户已通过身份验证 - Elements inside @guest tags shown, even though user is authenticated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM