Skip to content

8. 身份验证与授权

每个请求都会引出两个不同的问题:

  • 用户是谁?这就是身份验证:用户已经用用户名和密码表明了身份,之后的每个请求都必须证明它来自该用户;
  • 他们是否有权访问这个页面?这就是授权:在案例研究中,只有具有 ADMIN 角色的用户才能管理医生和客户。

身份证明必须伴随每一个请求。[Laravel] 通常把已登录用户的 ID 存储在其会话 中(参见关于作用域的一章),这是 Web 应用程序最简单的解决方案。而案例研究在它的所有版本([ASP.NET Core MVC]、[Spring MVC]、[NestJS]、[Flask])中,则改用令牌 (JWT (*JSON Web Token*)),我们在这里也将使用它:登录之后,服务器生成一个包含用户身份的令牌,并用一个密钥对其签名。令牌存储在 Cookie 中;浏览器在每次请求时把它发回;服务器验证签名。用户可以读取自己的令牌,但不能修改它:任何修改都会使签名失效。该格式是标准化的(RFC 7519),所有编程语言都能理解,并且令牌包含其过期日期。最重要的是,服务器不需要存储任何内容:任何知道密钥的服务器都可以验证令牌。

[Laravel] 拥有一个完整的身份验证系统,我们将原样使用其中的组件:

  • 身份验证 由一个*守卫*(guard)处理:这个对象会为每个请求识别出已通过身份验证的用户。[Laravel] 提供了一个读取会话的守卫;我们将用寥寥几行代码编写自己的守卫,由它来读取令牌。应用程序的其余部分只与守卫打交道:[auth()->user()]、[#[CurrentUser]],以及视图中的 [@auth] ;
  • 页面保护由路由中间件负责(见上一章):[auth] 要求用户已通过身份验证,[can:admin] 要求具备相应授权;
  • 授权由Gate描述(例如示例 26);
  • 密码由 [Hash] 门面进行哈希(使用 *bcrypt* 算法),尝试次数限制由 [RateLimiter] 门面实施(示例 27)。

令牌的生成与验证由 [firebase/php-jwt] 库负责,它是 [PHP] 中使用最广泛的库,由示例中的 [composer.json] 文件安装。

8.1. 示例 25:登录、令牌与受保护页面

25-jwt/
├── app/
│   ├── Auth/
│   │   ├── AuthService.php
│   │   ├── User.php
│   │   └── UsersService.php
│   └── Http/
│       └── Controllers/
│           ├── AuthController.php
│           └── ProfileController.php
├── bootstrap/
│   └── app.php
├── config/
│   ├── auth.php
│   └── jwt.php
├── resources/
│   └── views/
│       ├── auth/
│       │   └── login.blade.php
│       ├── layout.blade.php
│       └── profile/
│           └── profile.blade.php
├── routes/
│   └── web.php
└── ...

8.1.1. 配置:.env、config/jwt.php 和 config/auth.php

令牌使用密钥签名,而密钥不能硬编码。现在是真正把配置与代码分离的时候了。特定于某次安装的设置位于文件 [.env] 中(示例 01),现在它新增了两行:

1
2
3
# 签署 JWT 令牌的密钥(至少 32 个字符),及其有效期
JWT_SECRET=a-secret-key-of-at-least-32-characters-for-example-25
JWT_DURATION_MINUTES=60

对于所使用的算法(HMAC-SHA256),标准要求密钥至少为 256 位,即 32 字节;更短的密钥会被库拒绝。不过,代码并不读取 [.env] 文件:它读取的是应用程序的配置——存放在 [PHP] 文件集合中,位于 [config] 文件夹,每个文件都返回一个数组。我们创建 [config/jwt.php] 文件:

<?php
// config/jwt.php:JWT 令牌的配置,由 config('jwt.secret')... 读取
// env(NAME, default):环境变量或 .env 文件中的 NAME 变量
return [
    // 签署令牌的密钥(至少 32 个字符):绝不写在代码中
    'secret' => env('JWT_SECRET'),
    // 令牌的有效期,以分钟计
    'duration' => (int) env('JWT_DURATION_MINUTES', 60),
    // 承载令牌的 Cookie 的名称
    'cookie' => 'token',
];
  • 第 6 行:[env] 函数从进程的环境中读取变量,若没有,则从 [.env] 文件中读取;它的第二个参数是默认值。环境变量优先于文件:在生产环境中,密钥由环境提供,而文件 [.env] 中并不包含密钥;
  • 第 8 行:环境变量是字符串:[(int)] 将持续时间转换为整数。

代码使用 [config] 函数读取这些值:[config('jwt.secret')] 指的是 [jwt.php] 文件中的 [secret] 键。[env] 只在配置文件中调用:在生产环境中,命令 [php artisan config:cache] 会把整个配置合并为单个文件以加快处理速度,此后不再读取 [.env]。[config/auth.php] 文件用于配置身份验证:

<?php
// config/auth.php:身份验证。此文件补充 Laravel 的默认
// 配置(vendor/laravel/framework/config/auth.php)
return [
    // 默认使用的「守卫」:读取 JWT 令牌的那个
    'defaults' => [
        'guard' => 'jwt',
    ],
    'guards' => [
        // 使用 [jwt] 驱动的守卫,在 bootstrap/app.php 中定义(Auth::viaRequest)
        'jwt' => [
            'driver' => 'jwt',
        ],
    ],
];

[Laravel] 有自己的身份验证配置([vendor/laravel/framework/config/auth.php] 文件;见示例 01);应用程序的配置对其进行补充:应用程序提供的键会替换框架中的对应键,而其他键保持原值。我们声明一个名为 [jwt] 的守卫,其驱动为 [jwt] (第 12 行),并将其设为默认守卫(第 7 行)。驱动 [jwt] 在 [Laravel] 中并不存在:我们在 [bootstrap/app.php] 中定义它。

在 [Linux] 或 [macOS] 下,我们会用另一个密钥按如下方式启动应用程序:

JWT_SECRET="another-key-of-at-least-thirty-two-characters" php artisan serve

而在 [Windows] (PowerShell)下:

$env:JWT_SECRET="another-key-of-at-least-thirty-two-characters"
php artisan serve

8.1.2. 用户:app/Auth/User.php 和 UsersService.php

<?php
// app/Auth/User.php:一个用户。Authenticatable:Laravel 期望
// 已通过身份验证的用户所具有的接口

namespace App\Auth;

use Illuminate\Contracts\Auth\Authenticatable;

readonly class User implements Authenticatable
{
    public function __construct(
        public string $login,
        public string $name,
        public string $role,
        // 密码的哈希(从令牌读取的用户则为空)
        public string $passwordHash = '',
        // 对用户进行身份验证的令牌的内容
        public array $claims = [],
    ) {
    }

    // 用户的标识符:其登录名
    public function getAuthIdentifierName(): string
    {
        return 'login';
    }

    public function getAuthIdentifier(): string
    {
        return $this->login;
    }

    public function getAuthPasswordName(): string
    {
        return 'passwordHash';
    }

    public function getAuthPassword(): string
    {
        return $this->passwordHash;
    }

    // 会话的「记住我」令牌:这里用不到
    public function getRememberToken(): ?string
    {
        return null;
    }

    public function setRememberToken($value): void
    {
    }

    public function getRememberTokenName(): string
    {
        return '';
    }
}
  • 第 9 行:一个用户。[Laravel] 要求已通过身份验证的用户实现 [Authenticatable] 接口:通过该接口的方法,框架可获得用户的 ID、其哈希后的密码,以及“记住我”会话令牌(此处用不到)。在典型的应用程序中,用户表对应的 [Eloquent] 模型(下一章)会实现这个接口;
  • 第 12–18 行:登录名、姓名、角色、密码哈希,以及对该用户进行身份验证的令牌的内容(对于从用户列表中取得的用户则为空)。服务器绝不存储密码,即使已加密也不行:如果数据库被盗,密码也会随之被盗(而且很多人在所有地方都使用同一个密码)。它存储的是哈希函数的结果,哈希函数是单向函数:可以计算出密码的哈希,却无法从哈希还原出密码。要验证输入的密码,就计算它的哈希,并与存档的哈希比较。
<?php
// app/Auth/UsersService.php:内存中的用户(示例 28 和
// 案例研究会把它们放进数据库)

namespace App\Auth;

class UsersService
{
    // 我们绝不保存密码,只保存其 bcrypt 哈希,由以下命令一次性计算:
    // php -r "echo password_hash('marie', PASSWORD_BCRYPT);"
    private const USERS = [
        'marie' => ['Marie Pélissier', 'USER', '$2y$10$2DnOgGBiVcyc07su9rj2E.EvOoyPFzHN/h9PLKDuoW5P7UGtclW6W'],
        'admin' => ['Administrator', 'ADMIN', '$2y$10$m5o9euCi0EdgoZkLVw.UsO58RxJcqhMBfVrlLMCIOh2LyGSjuN29K'],
    ];

    public function find(string $login): ?User
    {
        if (! isset(self::USERS[$login])) {
            return null;
        }
        [$name, $role, $hash] = self::USERS[$login];
        return new User($login, $name, $role, $hash);
    }
}
  • 第 11–14 行:两个测试用户,硬编码在程序中(示例 28 和案例研究将用它们来填充数据库):每个登录名对应姓名、角色和密码哈希。哈希使用 bcrypt 算法生成,该算法专为密码设计。它有两个显著特点。第一,它是有意设计得慢的,且慢的程度可调(即代价(cost),这里设为 10:2^10 次计算循环,由此得到哈希中的 [$10$]):只需几十毫秒,用户毫无察觉,却让黑客尝试数十亿个密码的代价变得极其高昂。第二,它是加盐的:在哈希之前,会把随机生成的盐 与密码混合,并将其存放在哈希本身之中(即 [$10$] 后面的 22 个字符);因此,两个密码相同的用户会得到不同的哈希。这些哈希由 [password_hash] 函数(来自 [PHP] ,第 10 行)一次性计算好:在每个请求时都重新计算纯属不必要的时间浪费,因为应用程序在每个请求时都会重新构建。[bcrypt] 只考虑密码的前 72 个字节:案例研究会考虑到这一点;
  • 第 16–23 行:某个登录名对应的用户,或 [null]。[isset] 检查某个键是否存在;赋值 [[$name, $role, $hash] = ...] 对数组进行解构:每个变量接收对应的元素。

8.1.3. 认证服务:app/Auth/AuthService.php

<?php
// app/Auth/AuthService.php:密码和 JWT 令牌的检查

namespace App\Auth;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Support\Facades\Hash;
use Throwable;

class AuthService
{
    public function __construct(private UsersService $users)
    {
    }

    // 用户,如果登录名未知或密码错误则为 null。
    // Hash::check 用已存储哈希的盐值对输入的密码做哈希,
    // 然后比较两个结果
    public function validate(?string $login, ?string $password): ?User
    {
        if (! $login || $password === null) {
            return null;
        }
        $user = $this->users->find($login);
        if ($user === null || ! Hash::check($password, $user->passwordHash)) {
            return null;
        }
        return $user;
    }

    // 用户的 JWT 令牌,用密钥签名(HMAC-SHA256)
    public function createToken(User $user): string
    {
        $now = time();
        // 令牌的内容:「声明」(claims,关于用户的陈述)
        $claims = [
            'sub' => $user->login,
            'name' => $user->name,
            'role' => $user->role,
            'iat' => $now,
            'exp' => $now + config('jwt.duration') * 60,
        ];
        return JWT::encode($claims, config('jwt.secret'), 'HS256');
    }

    // 由令牌描述的用户,其签名和过期时间
    // 均有效;否则为 null(伪造、过期或无法读取的令牌)
    public function check(string $token): ?User
    {
        try {
            // decode 返回一个对象;(array) 将其转换为关联数组
            $claims = (array) JWT::decode($token, new Key(config('jwt.secret'), 'HS256'));
        } catch (Throwable) {
            return null;
        }
        return new User($claims['sub'], $claims['name'], $claims['role'], claims: $claims);
    }
}
  • 第 20–30 行:验证用户名和密码。[Hash::check] 使用已存储哈希中的盐对输入的密码进行哈希,并比较两个哈希。未知的用户名和错误的密码产生相同的结果,即 [null];
  • 第 33–45 行:生成令牌。其内容是一个关于用户的声明(claim)数组。其中一些有标准化的名称:[sub] (*subject*),用户的标识符;[iat] (*issued at*),创建日期;[exp] (*expiration*),过期日期。日期以自 1970 年 1 月 1 日起经过的秒数表示(即 [time()] 函数,来自 [PHP])。其他字段是可选的:这里是姓名和角色。[JWT::encode] 生成令牌,并使用 [HS256] 算法对其签名(HMAC-SHA256,一种使用共享密钥的签名);
  • 第 49–58 行:令牌验证。[JWT::decode] 验证签名和过期日期,然后返回声明(一个对象,由 [(array)] 转换为数组)。任何异常情况(伪造、过期或格式错误的令牌)都会引发异常;[catch (Throwable)] 会捕获所有异常([Throwable] 是 [PHP] 中所有异常和错误的接口;变量名在不使用时可以省略)。[Key] 对象把密钥与一个算法关联起来:指定了其他算法(或根本没有算法,即 [none])的令牌会被拒绝。有效的令牌会变成一个 [User],不含哈希,并带有它的声明(名为 [claims] 的参数)。

8.1.4. 守卫:bootstrap/app.php

<?php
// bootstrap/app.php:示例 25 的应用程序

use App\Auth\AuthService;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;

(require __DIR__.'/../../vendor/autoload.php')->addPsr4('App\\', __DIR__.'/../app/');

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        // 提供 Bootstrap 的路由(见示例 15)
        then: fn () => require __DIR__.'/../../common/bootstrap.php')
    ->withMiddleware(function (Middleware $middleware): void {
        // 令牌已经签名:承载它的 Cookie 不加密
        $middleware->encryptCookies(except: ['token']);
        // 请求受保护页面的匿名访客:转到 /login
        $middleware->redirectGuestsTo('/login');
    })
    ->withExceptions()
    ->booted(function () {
        // [jwt] 守卫驱动(见 config/auth.php):一个接收请求的函数,
        // 返回已通过身份验证的用户,匿名访客则返回 null
        Auth::viaRequest('jwt', function (Request $request) {
            $token = $request->cookie(config('jwt.cookie'));
            if ($token === null) {
                return null;
            }
            $user = app(AuthService::class)->check($token);
            if ($user === null) {
                // Cookie 存在但无效(过期、令牌被伪造):我们将其删除
                Cookie::queue(Cookie::forget(config('jwt.cookie')));
            }
            return $user;
        });
    })
    ->create();
  • 第 20 行:令牌已经签名;携带它的 Cookie 没有加密(示例 22),因此可以查看其内容;
  • 第 22 行:[auth] 中间件会将匿名访问者重定向到登录页面;
  • 第 28–39 行:[Auth::viaRequest] 用一个简单的函数定义守卫驱动:它接收请求,并返回已通过身份验证的用户,对于匿名访问者则返回 [null] 。只有在应用程序需要用户时才会调用它,而且一旦找到用户,[Laravel] 会在整个请求期间保留该用户(对于匿名访问者,则每个请求都会调用它)(中间件 [auth]、[auth()->user()]……)。它不会拒绝任何东西:它确定用户是谁。这就是身份验证。[app(AuthService::class)] 向容器请求一个对象(见示例 06):函数 [app] 使得在任何地方都能访问容器;
  • 第 34–39 行:如果浏览器发送了 Cookie,但其中的令牌无效(已过期或被篡改),我们就借此机会将其删除。[Cookie::forget] 创建一个已经过期的空 Cookie;[Cookie::queue] 将其加入队列:[AddQueuedCookiesToResponse] 中间件(位于 [web] 组中)会把它添加到响应中,无论该响应是什么。

8.1.5. 控制器

<?php
// app/Http/Controllers/AuthController.php:登录和注销

namespace App\Http\Controllers;

use App\Auth\AuthService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AuthController
{
    public function __construct(private AuthService $auth)
    {
    }

    public function home(): RedirectResponse
    {
        return redirect('/profile');
    }

    public function form(): View
    {
        return view('auth.login');
    }

    public function login(Request $request): View|RedirectResponse
    {
        $login = $request->input('login');
        $user = $this->auth->validate($login, $request->input('password'));
        if ($user === null) {
            // 故意含糊的消息:我们不说明是登录名还是密码有误
            return view('auth.login', ['login' => $login,
                'error' => 'Incorrect login or password.']);
        }
        // 令牌放在 Cookie 中:页面的 JavaScript 无法读取它
        // (httpOnly);来自其他站点的 POST 请求不会携带它
        // (sameSite);它与令牌同时过期(时长以分钟计)
        return redirect('/profile')->withCookie(cookie(config('jwt.cookie'),
            $this->auth->createToken($user), config('jwt.duration'),
            httpOnly: true, sameSite: 'lax'));
    }

    // 注销:仅限 POST(放在其他站点上的简单链接,
    // 不能在用户不知情时使其注销);我们删除 Cookie
    public function logout(): RedirectResponse
    {
        return redirect('/login')->withoutCookie(config('jwt.cookie'));
    }
}
  • 第 30–34 行:登录。如果登录失败,会重新显示表单,保留输入的用户名,并给出一条故意含糊的消息:如果说“用户名未知”,就会向黑客透露哪些用户名是存在的;
  • 第 39–41 行:如果成功,令牌存储在 Cookie 中,并将用户重定向到受保护的页面(PRG 模式)。该 Cookie 是 [httpOnly] 的:页面的 [JavaScript] 无法读取它,这可以保护令牌免受脚本注入(XSS)攻击;它是 [sameSite: 'lax'] 的:浏览器不会在源自其他站点的 POST 请求中发送它,这可以保护应用程序免受 CSRF 攻击(示例 18);它的生存期(以分钟计)与令牌相同。在生产环境中,对于 HTTPS,我们还会添加 [secure: true]:这样 Cookie 永远不会通过未加密的连接发送;
  • 第 46–49 行:注销会删除 Cookie([withoutCookie])。这是一个 POST 动作:放在其他站点上或图片中的指向 [/logout] 的简单链接,无法在用户不知情的情况下让其注销。请注意令牌的一个局限:令牌本身在过期之前一直有效。复制了它的人仍然可以使用它。这就是要限制令牌生存期的原因。
<?php
// app/Http/Controllers/ProfileController.php:仅限已通过身份验证的用户访问的页面

namespace App\Http\Controllers;

use App\Auth\User;
use Illuminate\Container\Attributes\CurrentUser;
use Illuminate\View\View;

class ProfileController
{
    // #[CurrentUser]:容器提供请求中已通过身份验证的用户,
    // 即守卫找到的那个(见 bootstrap/app.php)
    public function display(#[CurrentUser] User $user): View
    {
        return view('profile.profile', ['user' => $user]);
    }
}
  • 第 14 行:属性 [#[CurrentUser]] 向容器请求已通过身份验证的用户——即守卫找到的那个用户(有关参数属性,见示例 12)。该动作受 [auth] 中间件保护(见路由表):保证能收到一个用户。也可以通过 [auth()->user()] 或 [$request->user()] 获得它。

路由表:

<?php
// routes/web.php:示例 25 的路由

use App\Http\Controllers\AuthController;
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;

Route::get('/', [AuthController::class, 'home']);
Route::get('login', [AuthController::class, 'form']);
Route::post('login', [AuthController::class, 'login']);
Route::post('logout', [AuthController::class, 'logout']);

// [auth] 中间件:只有已通过身份验证的用户才能访问该路由
Route::get('profile', [ProfileController::class, 'display'])->middleware('auth');
  • 第 14 行:[auth] 中间件保护个人资料页面。对于匿名访问者,它会抛出 [AuthenticationException] 异常,[Laravel] 将其转换为重定向到登录页面([redirectGuestsTo])。[auth] 是一个别名——即 [Laravel] 与中间件 [Illuminate\Auth\Middleware\Authenticate] 关联的简短名称。一组路由可以一次性全部受到保护:[Route::middleware('auth')->group(...)]。

8.1.6. 视图

@extends('layout')

@section('content')
  <h1 class="h3">Login</h1>
  <form method="post" action="/login">
    @csrf
    <div class="mb-2">
      <label class="form-label" for="login">Login</label>
      <input class="form-control" id="login" name="login" value="{{ $login ?? '' }}" required>
    </div>
    <div class="mb-3">
      <label class="form-label" for="password">Password</label>
      <input class="form-control" type="password" id="password" name="password" required>
    </div>
    <button class="btn btn-primary" type="submit">Log in</button>
  </form>
  @isset($error)
    <div class="alert alert-danger mt-3">{{ $error }}</div>
  @endisset
  <p class="text-muted small mt-3">Test accounts (password = login): marie (USER), admin (ADMIN).</p>
@endsection
  • 第 6 行:登录表单与所有表单一样,受到防伪造请求的保护(示例 18);
  • 第 9 行:登录失败后,重新显示输入的登录名。
@extends('layout')

@section('content')
  <h1 class="h3">Hello {{ $user->name }}</h1>
  <p>Your role: <b>{{ $user->role === 'ADMIN' ? 'administrator' : 'user' }}</b>.</p>
  <p>The content of your token:</p>
  <table class="table table-sm w-auto">
    @foreach ($user->claims as $key => $value)
      <tr><td><code>{{ $key }}</code></td><td>{{ $value }}</td></tr>
    @endforeach
  </table>
  {{-- logging out: a POST form reduced to its button --}}
  <form method="post" action="/logout">
    @csrf
    <button class="btn btn-outline-secondary" type="submit">Log out</button>
  </form>
@endsection
  • 第 8–10 行:令牌的内容,仅作演示之用显示出来;
  • 第 13–16 行:注销,通过只有一个按钮的表单实现。

8.1.7. 执行

我们在未登录的情况下请求受保护的页面 [/profile] :

curl -i http://localhost:8000/profile
1
2
3
4
HTTP/1.1 302 Found
Location: http://localhost:8000/login
Content-Type: text/html; charset=utf-8
...

密码错误的情况:

Image

登录成功。使用 [curl] 时,必须先请求表单以获得防 CSRF 令牌和会话 Cookie(示例 18),然后在保留收到的 Cookie 的同时提交表单:

curl -c token.txt -b token.txt http://localhost:8000/login
curl -i -c token.txt -b token.txt -d "_token=...&login=marie&password=marie" http://localhost:8000/login
1
2
3
4
HTTP/1.1 302 Found
Location: http://localhost:8000/profile
Set-Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtYXJpZSIsIm5hbWUiOiJNYXJpZSBQXHUwMGU5bGlzc2llciIsInJvbGUiOiJVU0VSIiwiaWF0IjoxNzkwNDM5NjgyLCJleHAiOjE3OTA0NDMyODJ9.cvP1bi4zFamN79t2nqG7WXYLIF3kewt6UTOVb3swNtw; expires=Sat, 26 Sep 2026 17:21:22 GMT; Max-Age=3600; path=/; httponly; samesite=lax
...

令牌由三部分组成,以句点分隔,每一部分都经过 Base64 编码:头部、内容和签名。前两部分无需任何密钥即可解码:

{"typ":"JWT","alg":"HS256"}
{"sub":"marie","name":"Marie Pélissier","role":"USER","iat":1790439682,"exp":1790443282}

过期时间是创建之后一小时(3600 秒)。在浏览器中,个人资料页面显示的就是同样的内容:

Image

一个恶意用户修改了自己的令牌:他们把内容中的角色 [USER]*** 替换为 [ADMIN]***,将这一部分重新进行 Base64 编码,并保留原来的签名。服务器重新计算修改后内容的签名,而它已不再匹配:

curl -i -b "token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.<modified content>.cvP1bi4zFamN79t2nqG7WXYLIF3kewt6UTOVb3swNtw" http://localhost:8000/profile
1
2
3
4
HTTP/1.1 302 Found
Location: http://localhost:8000/login
Set-Cookie: token=deleted; expires=Fri, 26 Sep 2025 16:21:27 GMT; Max-Age=0; path=/; httponly; samesite=lax
...

伪造的令牌被拒绝并被删除(值 [deleted] 和已过期的日期指示浏览器删除该 Cookie)。要生成有效的签名,就必须知道密钥——因此保密并选择一个长而随机的密钥非常重要。

8.2. 示例 26:角色

示例 26 添加了一个管理页面,仅限角色 ADMIN 访问。只显示新增或修改的文件。

8.2.1. 授权:bootstrap/app.php

<?php
// bootstrap/app.php:示例 26 的应用程序

use App\Auth\AuthService;
use App\Auth\User;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Gate;

(require __DIR__.'/../../vendor/autoload.php')->addPsr4('App\\', __DIR__.'/../app/');

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        // 提供 Bootstrap 的路由(见示例 15)
        then: fn () => require __DIR__.'/../../common/bootstrap.php')
    ->withMiddleware(function (Middleware $middleware): void {
        // 令牌已经签名:承载它的 Cookie 不加密
        $middleware->encryptCookies(except: ['token']);
        // 请求受保护页面的匿名访客:转到 /login
        $middleware->redirectGuestsTo('/login');
    })
    ->withExceptions()
    ->booted(function () {
        // [jwt] 守卫驱动(见 config/auth.php):一个接收请求的函数,
        // 返回已通过身份验证的用户,匿名访客则返回 null
        Auth::viaRequest('jwt', function (Request $request) {
            $token = $request->cookie(config('jwt.cookie'));
            if ($token === null) {
                return null;
            }
            $user = app(AuthService::class)->check($token);
            if ($user === null) {
                // Cookie 存在但无效(过期、令牌被伪造):我们将其删除
                Cookie::queue(Cookie::forget(config('jwt.cookie')));
            }
            return $user;
        });
        // 一个命名的授权 [admin]:函数接收已通过身份验证的
        // 用户,并说明其是否具有所请求的权限
        Gate::define('admin', fn (User $user) => $user->role === 'ADMIN');
    })
    ->create();
  • 第 44 行:[Gate] 门面(“门”)定义了一个名为 [admin] 的授权 。该函数接收已通过身份验证的用户(以及可选的其他参数,例如要访问的对象),如果用户拥有所请求的权限,则返回 [true] 。权限可以通过多种方式验证:在代码中使用 [Gate::allows('admin')] 或 [Gate::authorize('admin')] (后者会抛出 403 异常),在视图中使用 [@can('admin')] ,在路由上使用 [can:admin] 中间件。当规则数量较多时,[Laravel] 建议按模型类将它们分组为策略 (*policies*)。

8.2.2. 路由表和控制器

<?php
// routes/web.php:示例 26 的路由

use App\Http\Controllers\AdminController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;

Route::get('/', [AuthController::class, 'home']);
Route::get('login', [AuthController::class, 'form']);
Route::post('login', [AuthController::class, 'login']);
Route::post('logout', [AuthController::class, 'logout']);

// [auth] 中间件:只有已通过身份验证的用户才能访问该路由
Route::get('profile', [ProfileController::class, 'display'])->middleware('auth');

// 两个中间件:[auth](已通过身份验证的用户),然后是 [can:admin](具有
// [admin] 授权的用户,见 bootstrap/app.php)
Route::get('admin', [AdminController::class, 'display'])->middleware(['auth', 'can:admin']);
  • 第 19 行:两个按顺序执行的中间件组件:[auth] 验证用户已通过身份验证(否则重定向到登录页面),然后 [can:admin] 验证用户拥有 [admin] 权限(否则返回 403 错误,*Forbidden*)。[:] 后面的文本是中间件参数,[Laravel] 会在 [$next] 之后把它传给中间件。这两种拒绝响应之间的差别很重要:对于已通过身份验证但不具备所需角色的用户,再去登录毫无意义,因为他们已经通过了身份验证。
<?php
// app/Http/Controllers/AdminController.php:仅限 ADMIN 角色访问的页面

namespace App\Http\Controllers;

use App\Auth\User;
use Illuminate\Container\Attributes\CurrentUser;
use Illuminate\View\View;

class AdminController
{
    public function display(#[CurrentUser] User $user): View
    {
        return view('admin.admin', ['name' => $user->name]);
    }
}

控制器不执行任何检查:那是中间件的职责。[Laravel] 还允许你使用属性,直接在动作本身上指定中间件:[#[Middleware('auth')]]、[#[Authorize('admin')]]。

8.2.3. 视图

@extends('layout')
{{-- the page of the 403 error, which Laravel displays by itself: a view
     errors/<code>.blade.php replaces the standard error page of this code --}}

@section('content')
  <div class="alert alert-danger">
    <h1 class="h4">Error 403</h1>
    <p class="mb-0">Access denied: this page is reserved for administrators.</p>
  </div>
  <p><a href="/profile">Back to the profile</a></p>
@endsection

403 错误页面:当发生 HTTP 错误时,[Laravel] 会查找视图 [errors/<code>.blade.php],并显示它来取代标准页面(见上一章)。无需声明任何内容。个人资料页面提供了指向管理页面的链接:

@extends('layout')

@section('content')
  <h1 class="h3">Hello {{ $user->name }}</h1>
  <p>Your role: <b>{{ $user->role === 'ADMIN' ? 'administrator' : 'user' }}</b>.</p>
  {{-- @can: the block is displayed only if the user has the [admin] authorization --}}
  @can('admin')
    <p><a href="/admin">The administration area</a></p>
  @else
    <p><a href="/admin">The administration area</a> (which is forbidden to you)</p>
  @endcan
  <p>The content of your token:</p>
  <table class="table table-sm w-auto">
    @foreach ($user->claims as $key => $value)
      <tr><td><code>{{ $key }}</code></td><td>{{ $value }}</td></tr>
    @endforeach
  </table>
  {{-- logging out: a POST form reduced to its button --}}
  <form method="post" action="/logout">
    @csrf
    <button class="btn btn-outline-secondary" type="submit">Log out</button>
  </form>
@endsection
  • 第 7–11 行:[@can] 指令仅在用户拥有权限时才显示它的代码块;[@else] 处理相反的情况。这样可以避免显示一个会导致错误的链接;不过,这只是一种便利措施:真正的保护来自路由。

8.2.4. 执行

角色为 USER 的 Marie 点击链接进入管理页面:

Image

而管理员则可以访问它:

Image

使用 [curl]:一个角色为 USER 的用户([token.txt] 文件,通过像示例 25 那样登录获得,但针对的是示例 26:这两个示例使用不同的密钥对令牌签名),然后是一个匿名访问者:

curl -i -b token.txt http://localhost:8000/admin
curl -i http://localhost:8000/admin
HTTP/1.1 403 Forbidden
Content-Type: text/html; charset=utf-8
...
        <div class="alert alert-danger">
    <h1 class="h4">Error 403</h1>
    <p class="mb-0">Access denied: this page is reserved for administrators.</p>
  </div>
...
HTTP/1.1 302 Found
Location: http://localhost:8000/login
...

逐个保护路由有一个缺陷:如果漏掉了某一个,该页面就会对所有人开放。案例研究将颠倒这一逻辑:所有路由都默认通过一个组受到保护,只有少数几个路由(登录页面、注册页面)被排除在外。

8.3. 示例 27:验证码和尝试次数限制

登录表单是攻击目标:程序每分钟可以尝试成千上万个密码(暴力破解攻击)。两种保护措施相辅相成:

  • 验证码(CAPTCHA) (*Completely Automated Public Turing test to tell Computers and Humans Apart*):一幅包含扭曲代码的图像,人类很容易读出,但程序很难识别;
  • 尝试次数限制:连续三次失败之后,客户端的 IP 地址会被封锁一分钟。

示例 27 以示例 25 为基础,并添加了这两项安全措施。

8.3.1. 验证码图像:app/Auth/CaptchaDrawing.php

<?php
// app/Auth/CaptchaDrawing.php:验证码的绘制,一个手工构建的
// SVG 图像(XML 文本)

namespace App\Auth;

class CaptchaDrawing
{
    public const WIDTH = 150;

    public const HEIGHT = 50;

    // 「字体」:每个字符是一组笔画的列表,每个笔画是 4 x 6 网格中
    // x、y 点的序列(y 轴向下)。
    // 彼此太容易混淆的字符已排除(0 O、1 I L)。
    private const FONT = [
        'A' => [[0, 6, 2, 0, 4, 6], [0.8, 3.8, 3.2, 3.8]],
        'B' => [[0, 0, 0, 6, 3, 6, 4, 5, 4, 4, 3, 3, 0, 3], [0, 0, 3, 0, 4, 1, 4, 2, 3, 3]],
        'C' => [[4, 1, 3, 0, 1, 0, 0, 1, 0, 5, 1, 6, 3, 6, 4, 5]],
        'D' => [[0, 0, 0, 6, 2.5, 6, 4, 4.5, 4, 1.5, 2.5, 0, 0, 0]],
        'E' => [[4, 0, 0, 0, 0, 6, 4, 6], [0, 3, 3, 3]],
        'F' => [[4, 0, 0, 0, 0, 6], [0, 3, 3, 3]],
        'G' => [[4, 1, 3, 0, 1, 0, 0, 1, 0, 5, 1, 6, 3, 6, 4, 5, 4, 3.5, 2.5, 3.5]],
        'H' => [[0, 0, 0, 6], [4, 0, 4, 6], [0, 3, 4, 3]],
        'J' => [[4, 0, 4, 5, 3, 6, 1, 6, 0, 5]],
        'K' => [[0, 0, 0, 6], [4, 0, 0, 3.5], [1.3, 2.6, 4, 6]],
        'M' => [[0, 6, 0, 0, 2, 3.5, 4, 0, 4, 6]],
        'N' => [[0, 6, 0, 0, 4, 6, 4, 0]],
        'P' => [[0, 6, 0, 0, 3, 0, 4, 1, 4, 2, 3, 3, 0, 3]],
        'Q' => [[1, 0, 3, 0, 4, 1, 4, 5, 3, 6, 1, 6, 0, 5, 0, 1, 1, 0], [2.5, 4.5, 4, 6.3]],
        'R' => [[0, 6, 0, 0, 3, 0, 4, 1, 4, 2, 3, 3, 0, 3], [2, 3, 4, 6]],
        'S' => [[4, 1, 3, 0, 1, 0, 0, 1, 0, 2, 1, 3, 3, 3, 4, 4, 4, 5, 3, 6, 1, 6, 0, 5]],
        'T' => [[0, 0, 4, 0], [2, 0, 2, 6]],
        'U' => [[0, 0, 0, 5, 1, 6, 3, 6, 4, 5, 4, 0]],
        'V' => [[0, 0, 2, 6, 4, 0]],
        'W' => [[0, 0, 1, 6, 2, 2.5, 3, 6, 4, 0]],
        'X' => [[0, 0, 4, 6], [4, 0, 0, 6]],
        'Y' => [[0, 0, 2, 3, 4, 0], [2, 3, 2, 6]],
        'Z' => [[0, 0, 4, 0, 0, 6, 4, 6]],
        '2' => [[0, 1, 1, 0, 3, 0, 4, 1, 4, 2, 0, 6, 4, 6]],
        '3' => [[0, 1, 1, 0, 3, 0, 4, 1, 4, 2, 3, 3, 1.5, 3], [3, 3, 4, 4, 4, 5, 3, 6, 1, 6, 0, 5]],
        '4' => [[3, 6, 3, 0, 0, 4, 4, 4]],
        '5' => [[4, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 5, 3, 6, 1, 6, 0, 5]],
        '6' => [[4, 1, 3, 0, 1, 0, 0, 1, 0, 5, 1, 6, 3, 6, 4, 5, 4, 4, 3, 3, 0, 3]],
        '7' => [[0, 0, 4, 0, 1.5, 6]],
        '8' => [[1, 3, 0, 2, 0, 1, 1, 0, 3, 0, 4, 1, 4, 2, 3, 3, 1, 3, 0, 4, 0, 5, 1, 6, 3, 6, 4, 5,
            4, 4, 3, 3]],
        '9' => [[4, 3, 1, 3, 0, 2, 0, 1, 1, 0, 3, 0, 4, 1, 4, 5, 3, 6, 1, 6, 0, 5]],
    ];

    // 几种深色,在浅色背景上易于阅读
    private const COLORS = ['#1f4e79', '#7b2d26', '#2e6b30', '#5b2c83', '#8a5a00', '#23395d', '#9c2a5b'];

    // 随机文本。random_int 是「密码学」生成器,
    // 不可预测(不同于 rand 或 mt_rand,其序列可能被猜出)
    public static function randomText(int $length): string
    {
        $alphabet = array_keys(self::FONT);
        $text = '';
        for ($i = 0; $i < $length; $i++) {
            $text .= $alphabet[random_int(0, count($alphabet) - 1)];
        }
        return $text;
    }

    // 在 $minimum 与 $maximum 之间随机取的浮点数
    private static function random(float $minimum, float $maximum): float
    {
        return $minimum + ($maximum - $minimum) * random_int(0, PHP_INT_MAX) / PHP_INT_MAX;
    }

    private static function color(): string
    {
        return self::COLORS[random_int(0, count(self::COLORS) - 1)];
    }

    public static function svg(string $text): string
    {
        $l = self::WIDTH;
        $h = self::HEIGHT;
        $pieces = ["<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"$l\" height=\"$h\" viewBox=\"0 0 $l $h\">",
            '<rect width="100%" height="100%" fill="#f5f7fa"/>'];

        // 字符:每个都经过放大、倾斜、平移,每个点
        // 都随机地略微移动
        $step = ($l - 20) / strlen($text);
        foreach (str_split($text) as $i => $character) {
            $scale = self::random(4.6, 5.6);    // 网格单位的大小,以像素计
            $angle = self::random(-0.35, 0.35);   // 旋转角度,以弧度计(约 ±20°)
            $cx = 10 + $step * ($i + 0.5) + self::random(-3, 3);    // 字符的中心
            $cy = $h / 2 + self::random(-4, 4);
            foreach (self::FONT[$character] as $stroke) {
                $d = [];
                for ($k = 0; $k < count($stroke); $k += 2) {
                    // 网格中的点,以 (2, 3) 为中心,经过扭曲、旋转、放置
                    $x = ($stroke[$k] - 2 + self::random(-0.2, 0.2)) * $scale;
                    $y = ($stroke[$k + 1] - 3 + self::random(-0.2, 0.2)) * $scale;
                    $px = $cx + $x * cos($angle) - $y * sin($angle);
                    $py = $cy + $x * sin($angle) + $y * cos($angle);
                    $d[] = sprintf('%s%.1f %.1f', $k === 0 ? 'M' : 'L', $px, $py);
                }
                $pieces[] = sprintf('<path d="%s" fill="none" stroke="%s" stroke-width="%.1f" '
                    .'stroke-linecap="round" stroke-linejoin="round"/>',
                    implode(' ', $d), self::color(), self::random(2.2, 3));
            }
        }

        // 3 条干扰线:穿过图像的曲线
        for ($n = 0; $n < 3; $n++) {
            $pieces[] = sprintf('<path d="M%.1f %.1f C%.1f %.1f %.1f %.1f %.1f %.1f" fill="none" '
                .'stroke="%s" stroke-width="1.3"/>',
                self::random(0, 20), self::random(5, 45), self::random(30, 60), self::random(0, 50),
                self::random(90, 120), self::random(0, 50), self::random(130, 150), self::random(5, 45),
                self::color());
        }
        $pieces[] = '</svg>';
        return implode('', $pieces);
    }
}

该图像采用 SVG 格式(*Scalable Vector Graphics*):一种以 XML(也就是文本)描述的矢量图形,由服务器不借助图形库直接生成,并由浏览器直接显示在页面上。

  • 第 16–49 行:一种极简的“字体”:每个字符是一组笔画的列表,每个笔画是 4 × 6 网格中的坐标 [x, y] 的列表。容易混淆的字符([0] 和 [O]、[1]、[I] 以及 [L])被排除在外;
  • 第 56–64 行:一个随机文本字符串,从字体中的字符中选取([array_keys],即表中的键)。来自 [rand] 和 [mt_rand] 的函数,[PHP] 产生的是可预测的数字序列(任何知道若干个值的人都能猜出后面的值):它们适用于模拟,不适用于安全场景。[random_int] 是一个密码学级别的生成器;它是不可预测的;
  • 第 67–70 行:一个随机浮点数,由一个随机整数生成([PHP_INT_MAX] 是 [PHP] 中最大的整数);
  • 第 77–118 行:绘制。每个字符都被随机缩放、旋转和移动,其每个点都有轻微偏移;每条线变成 SVG 的一个 [<path>] 元素([M]:移动,[L]:画线)。三条曲线([C]:贝塞尔曲线)横穿图像,以干扰识别程序。[sprintf] 函数用于格式化字符串:[%s] 向其中插入字符串,[%.1f] 插入带一位小数的数字。[str_split] 将字符串拆分为字符。

8.3.2. 验证码服务:app/Auth/CaptchaService.php

<?php
// app/Auth/CaptchaService.php:待处理的验证码,由服务器保存在
// 缓存中(见示例 20)

namespace App\Auth;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class CaptchaService
{
    // 验证码的有效期,以秒计
    private const LIFETIME = 600;

    public function generate(): Captcha
    {
        $text = CaptchaDrawing::randomText(5);
        // 随机标识符,无法猜出
        $id = Str::random(24);
        // 预期答案,在缓存中保存 10 分钟:之后缓存会自行
        // 忘记它
        Cache::put("captcha:$id", $text, self::LIFETIME);
        return new Captcha($id, CaptchaDrawing::svg($text));
    }

    // 验证码在所有情况下都会被消耗:一张图像只用一次
    public function check(?string $id, ?string $answer): bool
    {
        // pull:读取该值并将其从缓存中移除(不存在或已过期则为 null)
        $expected = $id ? Cache::pull("captcha:$id") : null;
        if ($expected === null || $answer === null) {
            return false;
        }
        return strcasecmp($expected, trim($answer)) === 0;
    }
}
  • 第 15–24 行:生成一个新的验证码:随机文本、一个无法猜到的随机标识符([Str::random] 同样使用密码学级别的生成器),以及图像。对于每个标识符,服务器会将预期的答案在缓存(示例 20)中存放十分钟:[Cache::put(key, value, seconds)]。到时间之后,缓存会自动将其丢弃。页面只收到标识符和图像:答案从不离开服务器。类 [Captcha] 将标识符和图像组合在一起;
  • 第 27–35 行:验证。[Cache::pull] 读取值并将其从缓存中移除:无论成功与否,验证码在任何情况下都会被消耗掉 。否则,程序就可以在同一幅图像上尝试所有可能的答案。比较时忽略大小写([strcasecmp] 对于两个相等的字符串返回 0,不区分大写和小写字母)并忽略输入两侧的空格([trim])。

8.3.3. 控制器:app/Http/Controllers/AuthController.php

<?php
// app/Http/Controllers/AuthController.php:登录(带验证码和尝试次数限制)和注销

namespace App\Http\Controllers;

use App\Auth\AuthService;
use App\Auth\CaptchaService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\View\View;

class AuthController
{
    // 最多失败 3 次,60 秒内
    private const MAX_FAILURES = 3;

    private const BLOCK_DURATION = 60;

    public function __construct(private AuthService $auth, private CaptchaService $captchas)
    {
    }

    public function home(): RedirectResponse
    {
        return redirect('/profile');
    }

    public function form(): View
    {
        return $this->loginPage();
    }

    public function login(Request $request): View|RedirectResponse
    {
        $login = $request->input('login');
        // 失败计数器的键:客户端的 IP 地址
        $key = 'login:'.$request->ip();

        // 1. 被封锁的地址根本不予理会
        if (RateLimiter::tooManyAttempts($key, self::MAX_FAILURES)) {
            $seconds = RateLimiter::availableIn($key);
            return $this->loginPage($login, "Too many attempts: try again in $seconds s.");
        }
        // 2. 先验证码(开销小),再密码(bcrypt,开销大)
        if (! $this->captchas->check($request->input('captchaId'), $request->input('captcha'))) {
            RateLimiter::hit($key, self::BLOCK_DURATION);
            return $this->loginPage($login, 'The image code is incorrect.');
        }
        $user = $this->auth->validate($login, $request->input('password'));
        if ($user === null) {
            RateLimiter::hit($key, self::BLOCK_DURATION);
            return $this->loginPage($login, 'Incorrect login or password.');
        }
        RateLimiter::clear($key);
        return redirect('/profile')->withCookie(cookie(config('jwt.cookie'),
            $this->auth->createToken($user), config('jwt.duration'),
            httpOnly: true, sameSite: 'lax'));
    }

    public function logout(): RedirectResponse
    {
        return redirect('/login')->withoutCookie(config('jwt.cookie'));
    }

    // 每次显示表单都会构建一个新的验证码
    private function loginPage(?string $login = null, ?string $error = null): View
    {
        return view('auth.login', ['login' => $login, 'error' => $error,
            'captcha' => $this->captchas->generate()]);
    }
}
  • 第 38 行:限制由 [RateLimiter] 门面(来自 [Laravel])处理,它在缓存中以某个键对“尝试次数”进行计数。这里的键是客户端的 IP 地址;
  • 第 41–44 行:被封锁的地址甚至不予理会。[tooManyAttempts(key, 3)] 在该键已达到 3 次尝试时为真;[availableIn] 返回封锁结束前剩余的秒数;
  • 第 46–54 行:验证码在密码之前验证;验证它几乎不花任何代价,而 [bcrypt] 是故意设计得很慢的。因此,输入了错误验证码的程序不会触发 [bcrypt]。每一次失败,无论是验证码错误还是密码错误,都会被计数:[RateLimiter::hit(key, 60)] 增加一次尝试,并将计数器的生存期设为 60 秒。因此,在第三次失败时,该地址会被封锁,直到从第一次失败算起的 60 秒结束;
  • 第 55 行:登录成功会清除失败的尝试记录;
  • 第 67–71 行:每次显示表单时都会生成一个新的验证码,即使在尝试失败之后也是如此。

[Laravel] 还提供了一个中间件组件 [throttle],用于限制某个路由的请求数量([->middleware('throttle:5,1')]:每分钟 5 个请求);我们选择只统计失败的尝试,以免给正常登录的用户造成不便。

8.3.4. 视图:resources/views/auth/login.blade.php

@extends('layout')

@section('content')
  <h1 class="h3">Login</h1>
  <form method="post" action="/login">
    @csrf
    <div class="mb-2">
      <label class="form-label" for="login">Login</label>
      <input class="form-control" id="login" name="login" value="{{ $login }}" required>
    </div>
    <div class="mb-2">
      <label class="form-label" for="password">Password</label>
      <input class="form-control" type="password" id="password" name="password" required>
    </div>
    <div class="mb-3">
      <label class="form-label" for="captcha">Copy the code of the image</label>
      {{-- the SVG image, built by the server: inserted without escaping --}}
      <div class="mb-1">{!! $captcha->svg !!}</div>
      {{-- the captcha identifier travels in a hidden field; the answer stays on the server --}}
      <input type="hidden" name="captchaId" value="{{ $captcha->id }}">
      <input class="form-control" id="captcha" name="captcha" autocomplete="off" required>
    </div>
    <button class="btn btn-primary" type="submit">Log in</button>
  </form>
  @if ($error)
    <div class="alert alert-danger mt-3">{{ $error }}</div>
  @endif
  <p class="text-muted small mt-3">Test accounts (password = login): marie (USER), admin (ADMIN).</p>
@endsection
  • 第 18 行:SVG 图像被原样插入页面,不做转义(示例 14)。这样做是合理的:这段 HTML 由服务器生成,不包含任何用户输入;
  • 第 20 行:验证码 ID,放在隐藏字段中;
  • 第 21 行:浏览器不会为该字段提示任何以前输入过的内容。

8.3.5. 执行

Image

抄错验证码的情况:

Image

三次失败的尝试之后,该地址被封锁:

Image

使用 [curl],用一个编造的验证码 ID 进行四次尝试(在像示例 25 那样获得会话 Cookie 和防 CSRF 令牌之后):

curl -b cookies.txt -d "_token=...&login=marie&password=marie&captchaId=abc&captcha=XXXXX" http://localhost:8000/login
1
2
3
4
      <div class="alert alert-danger mt-3">The image code is incorrect.</div>
      <div class="alert alert-danger mt-3">The image code is incorrect.</div>
      <div class="alert alert-danger mt-3">The image code is incorrect.</div>
      <div class="alert alert-danger mt-3">Too many attempts: try again in 60 s.</div>

即使密码正确,第四次尝试也会被拒绝,而且不会被处理。