gpt4 book ai didi

laravel - 如何处理 Laravel Passport 中的 OAuth 异常?

转载 作者:行者123 更新时间:2023-12-02 16:55:15 25 4
gpt4 key购买 nike

我正在研究 laravel 护照包。当我撤销 token 并访问经过身份验证的端点时,它会引发异常。

日志文件包含“资源所有者或授权服务器拒绝了请求”。为了处理异常,我创建了 OAuth 中间件并在其中放置了异常代码,如此链接中所述: https://www.kingpabel.com/oauth2-exception-custom-error-message/

public function handle($request, Closure $next)
{
//return $next($request);
try {
$response = $next($request);
// Was an exception thrown? If so and available catch in our middleware
if (isset($response->exception) && $response->exception) {
throw $response->exception;
}
return $response;
} catch (OAuthException $e) {
$data = [
// 'error' => $e->errorType,
// 'error_description' => $e->getMessage(),
'error' => 'Custom Error',
'error_description' => 'Custom Description',
];
return \Response::json($data, $e->httpStatusCode, $e->getHttpHeaders());
}
}

我想以 json 格式返回错误,例如:

{
"error": "Token is invalid!"
}

如果有人在这方面指导我,我将不胜感激。谢谢,

最佳答案

我设法通过这种方式得到它,在handler.php

use League\OAuth2\Server\Exception\OAuthServerException;
use Illuminate\Auth\AuthenticationException;
....

public function report(Exception $exception)
{
if ($exception instanceof OAuthServerException || $exception instanceof AuthenticationException) {

if(isset($exception->guards) && isset($exception->guards()[0]) ==='api')
response()->json('Unauthorized', 401) ;
else if ($exception instanceof OAuthServerException)
response()->json('Unauthorized', 401) ;
}

parent::report($exception);
}

然后为了防止浏览器上的跨源错误添加了一个中间件如下注意:使中间件在生产中安全内核.php

protected $middleware = [
....
\App\Http\Middleware\Cors::class,
];

cors.php

use Closure;

class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{

return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With')
->header('Access-Control-Allow-Credentials',' true');

}
}

关于laravel - 如何处理 Laravel Passport 中的 OAuth 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56750682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com