6

我提供了两个版本的security.yaml文件。根据API 平台文档的第二个版本。API 平台创建发送自定义用户提供程序。对于security.yamlAPI 平台文档中推荐的第二个选项,我需要创建两个额外的文件。我没有将它们附加到该主题,但如有必要会这样做。

但我认为问题出在 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平台/api包: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)%'
4

12 回答 12

14

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

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
于 2018-11-23T12:03:31.347 回答
7

问题是加密的私钥。

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

要识别私钥是否加密,请在任何文本编辑器中打开私钥。加密密钥的前几行类似于以下内容,带有 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 处理了这个错误就好了。

于 2018-02-09T18:08:30.427 回答
7

您需要在项目 .htaccess 文件或虚拟站点配置中允许授权标头(例如 /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>
于 2019-12-12T13:08:51.650 回答
5

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

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

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

于 2020-02-02T07:24:02.373 回答
1

使用此解决方案对我有用

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
于 2019-01-24T06:55:02.597 回答
1

我遇到了同样的问题,我通过删除防火墙登录并将其内容合并到防火墙 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
于 2020-01-20T09:12:22.793 回答
0

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

  1. 获取令牌
  2. 生成 SSH 密钥:正确
  3. 使用FormData发送身份验证请求

希望这能解决你的问题。

于 2018-02-07T16:49:48.817 回答
0

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

于 2018-02-08T04:59:04.777 回答
0

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

于 2020-08-27T16:13:51.833 回答
0

在这个文件 (project/public/ .htaccess ) 中添加:

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
于 2021-04-09T22:55:09.030 回答
0

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

于 2021-07-11T10:47:43.060 回答
0

以下答案未完成。

您需要创建一个 .htaccess 到 /public 文件夹并将这些行放在 section 中<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}::$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>
于 2022-01-20T13:40:27.217 回答