【问题标题】:401 JWT Token not found401 未找到 JWT 令牌
【发布时间】:2018-07-17 23:44:45
【问题描述】:

我提供了security.yaml 文件的两个版本。根据API Platform 文档的第二个版本。 API Platform 发送到creation a custom user provider。对于 API 平台文档中推荐的第二个选项 security.yaml,我需要创建两个额外的文件。我没有将它们附加到主题中,但如有必要会这样做。

但我认为问题出在 JWT 中。

环境:

  • 节点 v8.9.4
  • 铬 64.0.3282.119
  • Ubuntu 16.04
  • axios 版本:0.16.2
  • Vue.js 2.4.2
  • vue-axios 2.0.2
  • api-platform/api-pack: 1.0
  • Symfony 4.0.4

用户.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 }

标题

卷曲

带标题的卷曲

在浏览器中

.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)%'

【问题讨论】:

  • 绝地,我真的需要你的帮助。 @KévinDunglas
  • 我需要你的帮助 Dimitry,我也面临同样的问题,我不明白该怎么做,我看了你的回答,希望你能帮助我。

标签: symfony jwt api-platform.com lexikjwtauthbundle


【解决方案1】:

以下答案未完成。

您需要创建一个到 /public 文件夹的 .htaccess 并将此行放在 &lt;IfModule mod_rewrite.c&gt;&lt;/IfModule&gt; 部分 :

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}::$0 ^(/.+)/(.*)::\2$
    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}/$1 [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>

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      在这个文件中 (project/public/.htaccess) 只需添加以下内容:

      SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

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

          SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
          

          你可以在页面底部的githubLexikJWTAuthenticationBundle找到详细信息。

          【讨论】:

            【解决方案6】:

            我遇到了同样的问题,我通过删除防火墙登录并将其内容合并到防火墙 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
            

            【讨论】:

              【解决方案7】:

              您需要在项目的 .htaccess 文件或虚拟站点配置中允许 Authorization 标头(例如 /etc/apache2/sites-available/000-default.conf)

              <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>
              

              【讨论】:

                【解决方案8】:

                使用此解决方案对我有用

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

                【讨论】:

                  【解决方案9】:

                  我的解决方案是在 .htaccess 中添加它

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

                  【讨论】:

                  【解决方案10】:

                  问题是加密的私钥。

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

                  要识别私钥是否加密,请在任何文本编辑器中打开私钥。加密密钥的前几行类似于以下内容,带有 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”替换为加密输出密钥文件所需的文件名。

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

                  完成后,您会注意到文件中的 ENCRYPTED 字样已消失。

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

                  【讨论】:

                  • 我不明白该怎么做,我很痛苦。
                  • 我不是linux,而是windows
                  【解决方案11】:

                  尝试使用自定义密码重新生成私钥和公钥并将其设置在 .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

                  【讨论】:

                  • 感谢您的回答,但我已经尝试使用这些变体。第二个选项对我来说不是解决方案,需要使用our_db_provider。我想了解问题的根源。
                  • 如果你想使用 jwt 登录,你必须使用 json_login 而不是 form_login。您是否尝试在登录防火墙规则中设置自定义提供程序?
                  • 是的,我需要our_db_provider
                  • 更新github上的issue,最后评论:github.com/api-platform/api-platform/issues/557
                  【解决方案12】:

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

                  1. Obtain the token
                  2. Generate the SSH keys :妥妥的
                  3. 使用FormData发送验证请求

                  希望这能解决您的问题。

                  【讨论】:

                  猜你喜欢
                  • 2016-05-17
                  • 2018-01-15
                  • 2019-12-05
                  • 2019-12-11
                  • 1970-01-01
                  • 2017-08-22
                  • 2017-06-20
                  • 2020-08-07
                  • 2019-06-05
                  相关资源
                  最近更新 更多