繁体   English   中英

Lexik JWT 身份验证问题“凭据无效”

[英]Lexik JWT authentication problem "Invalid credentials"

我是 symfony 的新手,我正在使用 LexikJWTAuthenticationBundle 进行授权。 我正在使用 symfony 6.0.2 和 2.14 lexic 版本。 我正在使用 Postgresql 12.9。 我的安全.yaml:

security:
    enable_authenticator_manager: true
    # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
        App\Entity\User:
            algorithm: auto

    # https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email
    firewalls:
        login:
            pattern: ^/api/login
            stateless: true
            json_login:
                check_path: /api/login_check
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure

        api:
            pattern:   ^/api
            stateless: true
            jwt: ~
        main:
            lazy: true
            provider: app_user_provider

        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false


            # activate different ways to authenticate
            # https://symfony.com/doc/current/security.html#the-firewall

            # https://symfony.com/doc/current/security/impersonating_user.html
            # switch_user: true

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        - { path: ^/api/login, roles: PUBLIC_ACCESS }
        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }

when@test:
    security:
        password_hashers:
            # By default, password hashers are resource intensive and take time. This is
            # important to generate secure password hashes. In tests however, secure hashes
            # are not important, waste resources and increase test times. The following
            # reduces the work factor to the lowest possible values.
            Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
                algorithm: auto
                cost: 4 # Lowest possible value for bcrypt
                time_cost: 3 # Lowest possible value for argon
                memory_cost: 10 # Lowest possible value for argon

我的 fos_rest.yaml:

# Read the documentation: https://symfony.com/doc/master/bundles/FOSRestBundle/index.html
fos_rest: 
  body_listener:
      enabled: true
#    param_fetcher_listener:  true
#    allowed_methods_listener:  true
#    routing_loader: true
#    view:
#        view_response_listener:  true
#    exception:
#        codes:
#            App\Exception\MyException: 403
#        messages:
#            App\Exception\MyException: Forbidden area.
  format_listener:
       rules:
           - { path: ^/api, prefer_extension: true, fallback_format: json, priorities: [ json ] }

我的 lexik_jwt_authentication.yaml:

lexik_jwt_authentication:
    secret_key: '%env(resolve:JWT_SECRET_KEY)%'
    public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
    pass_phrase: '%env(JWT_PASSPHRASE)%'
    token_ttl: 3600

我的数据库配置正确,它正在工作,我的密码也正确我的用户实体是这样的:

<?php

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="`user`")
 */
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
   /**
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @ORM\Column(type="integer")
     */
    
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     */
    private $email;

    /**
     * @ORM\Column(type="json")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUserIdentifier(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see PasswordAuthenticatedUserInterface
     */
    public function getPassword(): string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }
}

我正在发送这个请求:

{
    "username": "azamjon",
    "password":"1234"
}

数据库有这些信息我做错了什么? 回应是:

{
    "code": 401,
    "message": "Invalid credentials."
} 

路线.yaml:

# controllers:
#     resource: ../src/Controller/
#     type: annotation

# kernel:
#     resource: ../src/Kernel.php
#     type: annotation

products:
    path: /api/product 
    controller: App\Controller\ProductController::indexAction
    methods : [GET]

products_store:
    path: /api/product_store
    controller: App\Controller\ProductController::createAction
    methods : [POST]

products_show:
    path: /api/product_show/{id}
    controller: App\Controller\ProductController::showAction
    methods : [GET]

products_delete:
    path: /api/product_delete/{id}
    controller: App\Controller\ProductController::deleteAction
    methods : [DELETE]

products_update:
    path: /api/product_update/{id}
    controller: App\Controller\ProductController::products_update
    methods : [PATCH]    

# register:
#   path: /api/register
#   controller: App\Controller\AuthController::register
#   methods: POST

api_login_check:
  path: /api/login_check

您可以使用选项user_identity_field: email因为默认设置为lexik_jwt_authentication.yaml中的username

#config/packages/lexik_jwt_authentication.yaml
lexik_jwt_authentication:
    secret_key: '%env(resolve:JWT_SECRET_KEY)%'
    public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
    pass_phrase: '%env(JWT_PASSPHRASE)%'
    token_ttl: 3600
    user_identity_field: email

您也可以将username_path添加到您的security.yaml以减少混淆:

#config/packages/security.yaml
json_login:
    check_path: /api/login_check
    success_handler: lexik_jwt_authentication.handler.authentication_success
    failure_handler: lexik_jwt_authentication.handler.authentication_failure
    username_path: email
    password_path: password

我有同样的问题,这是因为密码没有在我的数据库中散列......关心这个和配置:

# security.yaml

login:
    pattern: ^/api/login
    stateless: true
    json_login:
        check_path: /api/login_check
        username_path: email
        success_handler: lexik_jwt_authentication.handler.authentication_success
        failure_handler: lexik_jwt_authentication.handler.authentication_failure
# lexik_jwt_authentication.yaml

lexik_jwt_authentication:
    secret_key: '%env(resolve:JWT_SECRET_KEY)%'
    public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
    pass_phrase: '%env(JWT_PASSPHRASE)%'
    token_ttl: 3600
    user_identity_field: email

您必须检查在注册用户时完成的密码散列是否使用密码散列包完成

composer require symfony/password-hasher

因此,请务必遵循文档: symfony 中的密码哈希

并且,实现密码哈希来注册用户。

您尝试使用用户名登录,但是 symfony 等待电子邮件

providers:
  # used to reload user from session & other features (e.g. switch_user)
  app_user_provider:
    entity:
      class: App\Entity\User
      property: email

尝试将property: email替换为property: username

暂无
暂无

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

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