401 未找到 JWT 令牌

401 JWT Token not found

我提供了 security.yaml 文件的两个版本。根据 API Platform documentation. API Platform sends to the creation a custom user provider 的第二个版本。对于 API 平台文档中推荐的第二个选项 security.yaml,我需要创建两个附加文件。我没有把它们附在主题上,但如果需要的话会附上。

但我认为问题出在 JWT 中。

环境:

User.php

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

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

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

    /**
     * @ORM\Column(type="string", length=64)
     */
    private $password;

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

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    public function __construct() // add $username
    {
        $this->isActive = true;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function getSalt()
    {
        // you *may* need a real salt depending on your encoder
        // see section on salt below
        return null;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function getRoles()
    {
        return array('ROLE_ADMIN');
    }

    public function eraseCredentials()
    {
    }

    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->username,
            $this->password,
            // see section on salt below
            // $this->salt,
        ));
    }

    /** @see \Serializable::unserialize() */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->username,
            $this->password,
            // see section on salt below
            // $this->salt
        ) = unserialize($serialized);
    }
}

第一个选项security.yaml

security:

    encoders:
        App\Entity\User:
            algorithm: bcrypt

    providers:

        our_db_provider:
            entity:
                class: App\Entity\User
                property: username

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

        login:
            pattern:  ^/api/login
            stateless: true
            anonymous: true
            form_login:
                check_path:               /api/login_check
                success_handler:          lexik_jwt_authentication.handler.authentication_success
                failure_handler:          lexik_jwt_authentication.handler.authentication_failure
                require_previous_session: false

        api:
            pattern:   ^/api
            stateless: true
            provider: our_db_provider
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator

    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }

第二个选项security.yaml

security:

    encoders:
        App\Entity\User:
            algorithm: bcrypt

        App\Security\User\WebserviceUser: bcrypt

    providers:

        our_db_provider:
            entity:
                class: App\Entity\User
                property: username

        webservice:
            id: App\Security\User\WebserviceUserProvider

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

        login:
            pattern:  ^/api/login
            stateless: true
            anonymous: true
            provider: webservice
            form_login:
                check_path:               /api/login_check
                success_handler:          lexik_jwt_authentication.handler.authentication_success
                failure_handler:          lexik_jwt_authentication.handler.authentication_failure
                require_previous_session: false

        api:
            pattern:   ^/api
            stateless: true
            provider: our_db_provider
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator
    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }

Headers

卷曲

卷曲 headers

在浏览器中

.env

###> lexik/jwt-authentication-bundle ###
# Key paths should be relative to the project directory 
JWT_PRIVATE_KEY_PATH=var/jwt/private.pem
JWT_PUBLIC_KEY_PATH=var/jwt/public.pem
JWT_PASSPHRASE=d70414362252a41ce772dff4823d084d
###< lexik/jwt-authentication-bundle ###

lexik_jwt_authentication.yaml

lexik_jwt_authentication:
    private_key_path: '%kernel.project_dir%/%env(JWT_PRIVATE_KEY_PATH)%'
    public_key_path:  '%kernel.project_dir%/%env(JWT_PUBLIC_KEY_PATH)%'
    pass_phrase:      '%env(JWT_PASSPHRASE)%'

我遇到了这个确切的问题,我的建议是按照以下步骤解决您的问题:

  1. 获取token
  2. Generate the SSH keys : 正确
  3. 使用 FormData
  4. 发送身份验证请求

希望这能解决您的问题。

尝试使用自定义密码重新生成私钥和 public 密钥,并将其设置在 .env 文件中。

在 security.yaml 中更改登录防火墙:

...
firewalls
...
    login:
        pattern:  ^/api/login
        stateless: true
        anonymous: true
        provider: our_db_provider
        json_login:
            check_path: /api/login_check
            username_path: username
            password_path: password
            success_handler: lexik_jwt_authentication.handler.authentication_success
            failure_handler: lexik_jwt_authentication.handler.authentication_failure
...

如果没有帮助,请尝试使用 FosUserBundle

在composer.json中添加:

"friendsofsymfony/user-bundle": "dev-master"

在security.yaml中:

...
providers:
...
    fos_userbundle:
        id: fos_user.user_provider.username
...
firewalls
...
    login:
        pattern:  ^/api/login
        stateless: true
        anonymous: true
        provider: fos_userbundle
        json_login:
            check_path: /api/login_check
            username_path: username
            password_path: password
            success_handler: lexik_jwt_authentication.handler.authentication_success
            failure_handler: lexik_jwt_authentication.handler.authentication_failure
...

请参阅 ApiPlatform 文档中的 FOSUserBundle Integration

问题是加密私钥。

在传输或发送私钥之前,私钥通常会使用密码或密码进行加密和保护。当您收到加密私钥后,您必须解密私钥才能使用私钥。

要识别私钥是否加密,请在任何文本编辑器中打开私钥。加密密钥的前几行类似于以下内容,带有 ENCRYPTED 字:

---BEGIN RSA PRIVATE KEY---
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,AB8E2B5B2D989271273F6730B6F9C687
------
------
------
---END RSA PRIVATE KEY---

另一方面,未加密的密钥将具有以下格式:

---BEGIN RSA PRIVATE KEY---
------
------
------
---END RSA PRIVATE KEY---

加密密钥在大多数情况下不能直接在应用程序中使用。必须先解密

Linux 中的 OpenSSL 是解密加密私钥的最简单方法。使用以下命令解密加密的 RSA 密钥:

openssl rsa -in ssl.key.secure -out ssl.key

确保将“server.key.secure”替换为加密密钥的文件名,将“server.key”替换为加密输出密钥文件所需的文件名。

如果加密密钥受密码保护,请在出现提示时输入密码。

完成后,您会注意到文件中的加密措辞已经消失。

如果我没有使用Postman,那么我就不会看到Symfony的错误,这帮助我找到了问题的根源。如果 Lesik LexikJWTAuthenticationBundle 处理了这个错误就好了。

我的解决方案是将其添加到 .htaccess

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

我使用这个解决方案很有效

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

您需要在项目 .htaccess 文件或虚拟站点配置(示例 /etc/apache2/sites-available/000-default.conf)中允许授权 header

<Directory your_project_directory>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            Allow from all
            Require all granted
            RewriteEngine on
            RewriteCond %{HTTP:Authorization} ^(.*)
            RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
    </Directory>

我遇到了同样的问题,我通过 删除 防火墙 登录 并将其内容合并到防火墙 api 中来修复它,例如这个:

    api:
        pattern: ^/api
        stateless: true
        anonymous: true
        json_login:
            username_path: email
            check_path: /api/login_check
            success_handler: lexik_jwt_authentication.handler.authentication_success
            failure_handler: lexik_jwt_authentication.handler.authentication_failure
        guard:
            authenticators:
                - lexik_jwt_authentication.jwt_token_authenticator

为了解决这个问题,我在我的 Apache 配置文件中添加了以下行。

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=

您可以在页面底部 github LexikJWTAuthenticationBundle 中找到详细信息。

除了答案中提到的其他问题(和解决方案)之外,我还有一个与 LexikJWTAuthenticationBundle 相关的问题。和失眠。在 Insomnia 和“Bearer Token”中使用授权选项卡时,Insomnia 发送“授权”header 而不是“授权”。不确定 header 是否应该是 case-sensitive,但 LexikJWT 不使用“授权”,只使用“授权”。

在此文件中 (project/public/.htaccess) 只需添加:

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=

发送请求时,请确保您发送的内容是 JSON 而不是 HTML。

以下回答未完成。

您需要创建一个 .htaccess 到 /public 文件夹并将这些行放在 <IfModule mod_rewrite.c></IfModule> 部分 :

RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

完整的 .htaccess 给我这个并工作:

# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex index.php

# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options +FollowSymlinks

# Disabling MultiViews prevents unwanted negotiation, e.g. "/index" should not resolve
# to the front controller "/index.php" but be rewritten to "/index.php/index".
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the index.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %{REQUEST_URI}::[=11=] ^(/.+)/(.*)::$
    RewriteRule .* - [E=BASE:%1]

    # Sets the HTTP_AUTHORIZATION header removed by Apache
    #RewriteCond %{HTTP:Authorization} .+
    #RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0]

RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/index.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %{ENV:REDIRECT_STATUS} =""
    RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/ [R=301,L]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    # Rewrite all other queries to the front controller.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 307 ^/$ /index.php/
        # RedirectTemp cannot be used instead
</IfModule>
</IfModule>

对于 Symfony 5.3 及更高版本 anonymous: true 属性已从 security.yaml 文件中删除,

我通过这样替换来修复我的问题:

access_control:
    - { path: ^/api/login, roles: PUBLIC_ACCESS }
    - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }