Laravel政策:在项目中没有使用,只有403

问题描述 投票:0回答:2

我正在尝试使用laravel策略来检查故事是否“可见”,如果不是,则通过身份验证的用户是否拥有该故事(在这种情况下,他仍然可以查看该故事)。我使用[]设置了政策

php artisan make:policy StoryPolicy --model=Story

我设置了所需的检查,以查看通过身份验证的用户是否可以看到故事

<?php

namespace App\Policies;

use App\User;
use App\Story;
use Illuminate\Auth\Access\HandlesAuthorization;

class StoryPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the story.
     *
     * @param  \App\User  $user
     * @param  \App\Story  $story
     * @return mixed
     */
    public function view(User $user, Story $story)
    {
        if ($story->visibility == 'visible') {
            return true;
        } else {
            return $story->user_id == $user->id;
        }
    }
}

我在AuthServiceProvider中注册策略

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Story' => 'App\Policies\StoryPolicy'
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
    }
}

据我了解,我应该能够在控制器中使用此策略。这就是我所做的。

<?php

namespace App\Http\Controllers;

use App\Storyblock;
use App\User;
use Illuminate\Http\Request;
use App\Category;
use App\Story;

class StoryController extends Controller
{

    public function __construct(){
        $this->middleware('auth')->except('show');
    }

    //  GET shows the story page
    public function show(Story $story) {
        $this->authorize('view',$story);

        return view('story.show', compact('story'));
    }

}

但是这总是会导致403

我已经尝试了很多事情,改变了策略的设置方式,如果一切正确的话,改变了逻辑。在经过4个小时的在线在线搜索后,我未能给出答案。

[此外,在我的phpStorm中,我注意到我的策略文件显示为红色,在整个项目中没有使用。这使我认为我以某种方式无法将它们导入到我的AuthServiceProvider中]

我正在尝试使用laravel策略来检查故事是否“可见”,如果不是,则通过身份验证的用户是否拥有该故事(在这种情况下,他仍然可以查看该故事)。我使用php ...

php laravel laravel-5.7
2个回答
0
投票

我没有看到您的所有代码,但是当您要访问lavarel资源并且您没有scrf令牌时,会收到此消息,请确保所有视图或应用程序视图标头上都具有此信息

<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">

0
投票

您已指定show方法不会分配auth中间件,因此可能没有经过身份验证的用户。从策略文档中:

© www.soinside.com 2019 - 2024. All rights reserved.