如果Laravel 5.5中的请求授权失败,则重定向 [英] Redirect if request authorization is failed in Laravel 5.5
问题描述
如果授权失败,我正在尝试重定向请求.我有以下代码:
I am trying to redirect request if authorization is failed for it. I have following code:
class ValidateRequest extends Request{
public function authorize(){
// some logic here...
return false;
}
public function rules(){ /* ... */}
public function failedAuthorization() {
return redirect('safepage');
}
}
默认情况下,我被重定向到403错误页面,但是我想指定一些特定的路由.我注意到方法failedAuthorization()
正在运行,但是redirect()
方法不起作用...
By default I am redirected to the 403 error page, but I would like to specify some specific route. I noticed that method failedAuthorization()
is run, but redirect()
method does not work...
以前,此代码可与Laravel 5.1配合使用,但是我使用了forbiddenResponse()
方法来重定向错误的请求.如何使用新的LTS版本修复它?
Previously this code worked well with Laravel 5.1 but I used forbiddenResponse()
method to redirect wrong request. How can I fix it with new LTS version?
推荐答案
看起来不可能直接从自定义ValidateRequest
类进行redirect()
.我发现的唯一解决方案是创建自定义异常,然后在Handler类中对其进行处理.因此,现在它可以与以下代码一起使用:
Looks like it is impossible to redirect()
directly from the custom ValidateRequest
class. The only solution that I found is create custom exception and than handle it in the Handler class. So, now it works with following code:
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;
return $this;
}
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 s,而使用Laravel 5.1时,相同的操作(和相同的代码)仅花费0.3 s
So, it works, but much more slower than I expected... Simple measuring shows that handling and redirecting take 2.1 s, but with Laravel 5.1 the same action (and the same code) takes only 0.3 s
将NotAuthorizedException::class
添加到$dontReport
属性完全没有帮助...
Adding NotAuthorizedException::class
to the $dontReport
property does not help at all...
更新
在php 7.2中运行速度更快,耗时0.7 s
It runs much more faster with php 7.2, it takes 0.7 s
这篇关于如果Laravel 5.5中的请求授权失败,则重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!