【问题标题】:Trying to use policies in Laravel 5.2, following documentation I still can't get it to work尝试在 Laravel 5.2 中使用策略,按照文档我仍然无法让它工作
【发布时间】:2016-08-10 22:37:14
【问题描述】:

我查看了文档https://laravel.com/docs/5.2/authorization#controller-authorization 和一些在线教程,我确信我做的一切都是正确的。但是我无法让政策在 laravel 5.2 中工作 我创建了一个策略类

use App\User;
use App\Gallery;
use Illuminate\Auth\Access\HandlesAuthorization;
class GalleryPolicy
{
    use HandlesAuthorization;
    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function saveTitle(User $user, Gallery $gallery)
    {
        return true;
        // return $user->id === $gallery->user_id;
    }
}

我是这样在 AuthServiceProvider 中注册的

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    'App\Gallery' => 'App\Policies\GalleryPolicy',
];

现在在我的控制器中我这样称呼它

    $gallery = Gallery::where('hash', $request->gallery)->first();
    $this->authorize('saveTitle', $gallery);

我得到这个输出: 哎呀,看起来像出事了。 Handler.php 第 107 行中的 1/1 HttpException:此操作未经授权。

【问题讨论】:

  • 你也有公共函数boot(GateContract $gate) { $this->registerPolicies($gate);在你的 AUthServiceProvider 中? Laravel 实际上建议引用类 \App\Model::class (对于模型和策略)
  • 它看起来好像在工作?什么不工作?
  • 看来我没有登录,这就是它失败的原因。我傻了

标签: laravel laravel-5.2


【解决方案1】:

据我所知,您的 Policy 有效,但您没有捕获 authorize 方法引发的异常。

如果授权失败,AuthorizesRequests trait 会抛出 HttpException。如果您没有捕捉到它,异常处理程序会捕捉到异常,并按照您在问题中所写的那样向您显示。

<?php

class GalleryController extends Controller {
    /**
     * Example action.
     */
    public function show() {
        try {
            $gallery = Gallery::where('hash', $request->gallery)->first();
            $this->authorize('saveTitle', $gallery);
        } catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
            // Handle the unauthorized request's response here.
        }
    }
}

有关更多信息,请参阅特征源:(从 5.1 开始,但大部分内容相同。):

特别是:$message = '此操作未经授权。'

/**
 * Throw an unauthorized exception based on gate results.
 *
 * @param  string  $ability
 * @param  mixed|array  $arguments
 * @param  string  $message
 * @param  \Exception  $previousException
 * @return \Symfony\Component\HttpKernel\Exception\HttpException
 */
protected function createGateUnauthorizedException($ability, $arguments, $message = 'This action is unauthorized.', $previousException = null)
{
    return new HttpException(403, $message, $previousException);
}

【讨论】:

    猜你喜欢
    • 2016-08-12
    • 2013-01-23
    • 1970-01-01
    • 2014-01-18
    • 2020-05-08
    • 2016-07-19
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多