Auth 授权的异常捕获

上技师

路由中我们有使用 auth 中间件,所以打开修改 App\Http\Middleware\Authenticate.php 中间件。

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use App\Exceptions\AuthException;

class Authenticate extends Middleware
{
    /**
     * 重写未授权方法
     *
     * @param $request
     * @param array $guards
     * @return void
     * @throws AuthException
     */
    protected function unauthenticated($request, array $guards): void
    {
        throw new AuthException();
    }
}

AuthException 是我自定义的异常类,最终返回的是 response 响应。

原理

App\Http\Middleware\Authenticate 继承 Illuminate\Auth\Middleware\Authenticate,父类中有个 unauthenticated 方法,抛出的异常是 Illuminate\Auth\AuthenticationException,我们只需要重写这个方法就好了。
原中间件 App\Http\Middleware\Authenticate 中只有 redirectTo 这个方法。重写 unauthenticated 方法后,redirectTo 就可以删除了。

其他方法

App\Exceptions\Handler.php 中,向 render 方法中添加如下代码:

<?php
namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Middleware\Authenticate;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use App\Exceptions\AuthException;

class Handler extends ExceptionHandler
{
    ...
     public function render($request, Exception $exception)
    {
        if ($exception instanceof AuthenticationException) {
            throw new AuthException();
        }
        return parent::render($request, $exception);
    }
}

在论坛上看了也不知道是谁的文章,说 render 方法中不能过多的使用 instanceof 所以打开源码简单看了一下。

本作品采用《CC 协议》,转载必须注明作者和本文链接
未知的永远是最精彩的!
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!