Laravel form表单中认证失败如何返回自定义消息?

Laravel6.x 请问当authorize方法返回false时,如何自定义消息?

class AmazonOrderRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        Log::debug($this->route('access_id'));
        //アクセス認証
        $api_authority = DB::table('api_authentication')->where('api_name', 'HomePage')->first();
        if (!$api_authority || $api_authority->access_id != $this->json()->get('access_id','') ) {
            return false;
        }
        return true;
    }
}

期望得到的结果

Laravel form表单中认证失败如何返回自定义消息?

实际得到的结果

Laravel form表单中认证失败如何返回自定义消息?

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

在当前表单请求验证类中 重写父类 FormRequest 的 failedAuthorization 方法

protected function failedAuthorization()
{
    throw(new HttpResponseException(response()->json([
        'code'=>403,
        'msg'=>'您没有权限进行此操作'
    ],403)));
}

或者在 App\Exceptions\Handler.php 中捕捉 FormRequest 抛出的 AuthorizationException 异常

use Illuminate\Auth\Access\AuthorizationException;
public  function  render($request, Exception $exception) {
    if ($exception instanceof AuthorizationException) {
        return response([
            // ..
        ], 403);
    }
}

建议第一种就可以

1年前 评论
Partrick (楼主) 1年前
讨论数量: 5

app\Exceptions\Handler里面register

      $this->renderable(function (Illuminate\Validation\UnauthorizedException $e, $request) {
                return response()->json([
                     'success' => false,
                     'message' => ''
                ]);
        });

6.x版本应该大差不差

1年前 评论

在Request类里重写failedAuthorization,抛出你要的错误信息就好了 我是8,你6试一下

protected function failedAuthorization()
{
    throw new AuthorizationException('自定义认证失败错误信息');
}
1年前 评论
自由与温暖是遥不可及的梦想

表单验证《Laravel 9 中文文档》

不需要管authorizetrue 还是 false

1年前 评论

在当前表单请求验证类中 重写父类 FormRequest 的 failedAuthorization 方法

protected function failedAuthorization()
{
    throw(new HttpResponseException(response()->json([
        'code'=>403,
        'msg'=>'您没有权限进行此操作'
    ],403)));
}

或者在 App\Exceptions\Handler.php 中捕捉 FormRequest 抛出的 AuthorizationException 异常

use Illuminate\Auth\Access\AuthorizationException;
public  function  render($request, Exception $exception) {
    if ($exception instanceof AuthorizationException) {
        return response([
            // ..
        ], 403);
    }
}

建议第一种就可以

1年前 评论
Partrick (楼主) 1年前

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