gpt4 book ai didi

laravel-5 - Laravel 中请求授权失败时重定向

转载 作者:行者123 更新时间:2023-12-03 09:02:12 24 4
gpt4 key购买 nike

如果授权失败,我正在尝试重定向请求。我有以下代码:

class ValidateRequest extends Request{
public function authorize(){
// some logic here...
return false;
}

public function rules(){ /* ... */}

public function failedAuthorization() {
return redirect('safepage');
}
}

默认情况下我会被重定向到 403 错误页面,但我想指定一些特定的路由。我注意到方法 failedAuthorization() 已运行,但 redirect() 方法不起作用...

以前,这段代码在 Laravel 5.1 中运行良好,但我使用 forbiddenResponse() 方法来重定向错误的请求。如何使用新的 LTS 版本修复该问题?

最佳答案

看起来不可能直接从自定义 ValidateRequestredirect()。我发现的唯一解决方案是创建自定义异常并在 Handler 类中处理它。所以,现在它可以使用以下代码:

更新:方法 redirectTo() 已更新,使解决方案适用于 Laravel 6.x 及更高版本

app/Requests/ValidateRequest.php

class ValidateRequest extends Request{
public function authorize(){
// some logic here...
return false;
}

public function rules(){
return [];
}

public function failedAuthorization() {
$exception = new NotAuthorizedException('This action is unauthorized.', 403);

throw $exception->redirectTo("safepage");
}
}

app/Exceptions/NotAuthorizedException.php

<?php

namespace App\Exceptions;

use Exception;

class NotAuthorizedException extends Exception
{
protected $route;

public function redirectTo($route) {
$this->route = $route;

abort(Redirect::to($route));
}

public function route() {
return $this->route;
}
}

app/Exceptions/Handler.php

...
public function render($request, Exception $exception){
...

if($exception instanceof NotAuthorizedException){
return redirect($exception->route());
}

...
}

所以,它可以工作,但比我预期的要慢得多...简单的测量表明处理和重定向需要 2.1 秒,但在 Laravel 5.1 中相同的操作(和相同的代码)只需要 0.3 秒

NotAuthorizedException::class 添加到 $dontReport 属性根本没有帮助...

更新

使用 php 7.2 运行速度更快,需要 0.7 秒

关于laravel-5 - Laravel 中请求授权失败时重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49403226/

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