更改无效范围的消息

时间:2019-06-15 04:44:44

标签: php laravel laravel-5 laravel-5.5 laravel-passport

如何更改Laravel Passport中提供的无效作用域消息 enter image description here

3 个答案:

答案 0 :(得分:0)

您可以像在{strong>您的控制器中那样,将其作为Exception来捕获:

try {

// Whatever you are doing which leads to such error.


} catch (MissingScopeException $e) {
    return response()->json(['message' => 'YOUR DESIRED MESSAGE.']);
}

顺便说一下,this is where导致了这种异常。

答案 1 :(得分:0)

尝试更新render function文件中的app/Exceptions/Handler.php

public function render($request, Exception $exception)
    {
        if ($exception instanceof \Laravel\Passport\Exceptions\MissingScopeException) 
        {
          return response()->json(['message' => 'your message here']); 
          //abort(401); 
        }

        return parent::render($request, $e);
    }

答案 2 :(得分:0)

我正在使用laravel/framework v8.10.0laravel/passport v10.0.1

如果仅将Passport用于API,则可以直接在中间件中更改throw异常。

步骤:

  1. 转到app/Http/Kernel.php
  2. $routeMiddleware数组中,您需要包含以下行: 'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class
  3. 使用Ctrl +单击(Windows)或Cmd +单击(MacOS),转到CheckForAnyScope中间件。
  4. CheckForAnyScope中间件中,转到handle函数并在该行之前: throw new MissingScopeException($scopes);添加您的自定义错误响应。

示例代码:

public function handle($request, $next, ...$scopes)
{
        if (! $request->user() || ! $request->user()->token()) {
            throw new AuthenticationException;
        }

        foreach ($scopes as $scope) {
            if ($request->user()->tokenCan($scope)) {
                return $next($request);
            }
        }

        // Custom error response
        return response()->json(['success' => false, 'errors' => ['This type of user cannot do this action.'], 'data' => null]);

        // This line can be commented or deleted.
        throw new MissingScopeException($scopes);
}