Symfony 6和LexikjwtauthenticationBundle 2:JSON Web令牌(JWT)auth
#php #symfony #jwt #authentication

概括

JWT,JSON Web代币,是开放的Internet协议标准之一,定义为“在RFC 7519中代表两方转让的索赔的紧凑型URL安全手段”。

它们很受欢迎,并广泛用于身份验证Web API的工作地点。它们也可以在SSO又名单登录中找到。

名为lexikjwtauthenticationbundle的Symfony大捆绑包之一,为我们提供了将JWT访问控制添加到应用程序ð

的力量ð¥

本文显示了如何实现JWT进行身份验证。此外,通过在Symfony的Security -Bundle中与access control合作,它可用于授权。
我们去。

环境

参考


教程

概述

步骤如下:

  1. 准备Symfony Project
  2. 安装捆绑包
  3. 配置
  4. 通过命令行测试

1.准备

1-1。创建Symfony项目

这篇文章可能很有用:

2.建立JWT身份验证和授权

2-1。安装LexikjwtauthenticationBundle

感谢koude0Choosit (lexik),命令行将带您一步!

$ composer require "lexik/jwt-authentication-bundle"

输出为:

Info from https://repo.packagist.org: #StandWithUkraine
Using version ^2.16 for lexik/jwt-authentication-bundle
./composer.json has been updated
Running composer update lexik/jwt-authentication-bundle
Loading composer repositories with package information
Updating dependencies
Lock file operations: 6 installs, 0 updates, 0 removals
  - Locking lcobucci/clock (2.2.0)
  - Locking lcobucci/jwt (4.0.4)
  - Locking lexik/jwt-authentication-bundle (v2.16.0)
  - Locking namshi/jose (7.2.3)
  - Locking stella-maris/clock (0.1.6)
  - Locking symfony/polyfill-php56 (v1.20.0)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 6 installs, 0 updates, 0 removals
  - Downloading stella-maris/clock (0.1.6)
  - Downloading lcobucci/clock (2.2.0)
  - Downloading namshi/jose (7.2.3)
  - Downloading lcobucci/jwt (4.0.4)
  - Downloading lexik/jwt-authentication-bundle (v2.16.0)
  - Installing stella-maris/clock (0.1.6): Extracting archive
  - Installing lcobucci/clock (2.2.0): Extracting archive
  - Installing symfony/polyfill-php56 (v1.20.0)
  - Installing namshi/jose (7.2.3): Extracting archive
  - Installing lcobucci/jwt (4.0.4): Extracting archive
  - Installing lexik/jwt-authentication-bundle (v2.16.0): Extracting archive
Generating optimized autoload files
116 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

Symfony operations: 1 recipe (9ad0fc3489604428ab4d55a826a98856)
  - Configuring lexik/jwt-authentication-bundle (>=2.5): From github.com/symfony/recipes:main
Executing script cache:clear [OK]
Executing script assets:install public [OK]

 What's next? 


Some files have been created and/or updated to configure your new packages.
Please review, edit and commit them: these files are yours.

No security vulnerability advisories found

此外,namshi/joselcobucci/jwt是关键包。

生成了配置文件,将其放置为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)%'

另外,下面的行被附加到.env

###> lexik/jwt-authentication-bundle ###
JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pem
JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pem
JWT_PASSPHRASE=(your-secret)
###< lexik/jwt-authentication-bundle ###

2-2。生成键盘

好吧,实际上,钥匙本身尚未生成。但是,这没有问题,因为捆绑包也很好地帮助我们生成了一对:)

$ php bin/console lexik:jwt:generate-keypair

然后您会看到:

$ ls config/jwt/
private.pem  public.pem

2-3。配置路线和防火墙

JSON Login上还剩几个步骤,以实现“基于用户名(或电子邮件)和密码提供这些令牌的端点”。

编辑config/routes.yaml添加一条路由以进行身份​​验证或授权:

  controllers:
      resource: ../src/Controller/
      type: attribute
+ jwt_auth:
+     path: /auth

然后编辑config/packages/security.yaml将路线用作auth门:

  security:
      # ...
      firewalls:
          # ...
+         jwt_auth:
+             pattern: ^/auth
+             stateless: true
+             json_login:
+                 check_path: jwt_auth
+                 success_handler: lexik_jwt_authentication.handler.authentication_success
+                 failure_handler: lexik_jwt_authentication.handler.authentication_failure
          main:
              # ...

此外,仅对于5.4,还需要以下内容:

  security:
+     enable_authenticator_manager: true

3.让我们玩:与JWT访问API

3-1。准备路线

让我们创建API路线。

$ php bin/console make:controller api

输出为:

 created: src/Controller/ApiController.php
 created: templates/api/index.html.twig


  Success! 


 Next: Open your new controller class and add some pages!

3-2。准备路线和防火墙

然后,让JWT在路线中必要:

  security:
      # ...
      firewalls:
          # ...
          jwt_auth:
              # ...
          api:
+             pattern: ^/api
+             stateless: true
+             jwt: ~
          # ...
          main:
              # ...
      access_control:
          # ...
+         - { path: ^/api, roles: IS_AUTHENTICATED_FULLY }

3-3。通过要求服务器生成它来获取令牌

我们现在准备好了。使用koude6连接到/auth以获取令牌:

$ curl -X POST \
      -H "Content-Type: application/json" \
      -d '{"username":"your-username","password":"your-password"}' \
      https://your-domain/auth

此外,如果您必须抑制TLS错误,请附加koude7/koude8

您会得到:

{"token":"xxx.xxx.xxx"}

3-4。使用令牌

$ curl \
      -o /dev/null -s -w "HTTP Response = %{http_code}\n" \
      https://your-domain/api

没有有效的令牌,您将看到401误差ðµ因访问被拒绝。

接下来,尝试包括您的令牌:

$ curl \
      -o /dev/null -s -w "HTTP Response = %{http_code}\n" \
      -H "Authorization: Bearer xxx.xxx.xxx" \
      https://your-domain/api

您会看到200ð(好吧,当您的应用程序找不到绑定到路线的控制器时,您将获得404。 是的,接受了ð