Laravel 5.6策略在远程服务器上无法正常运行

时间:2018-08-19 08:33:21

标签: php laravel laravel-5 laravel-authorization

我创建一个名为LetterPolicy的策略,这是代码

    namespace App\Policies;

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

    class LetterPolicy
    {
        use HandlesAuthorization;

        /**
         * Create a new policy instance.
         *
         * @return void
         */

        public function __construct()
        {
            //
        }

        public function update(User $user, Letter $letter)
        {
            return($user->id === $letter->user_id || $user->role_id===1 ) ;
        }
    }

这是authserviceprovider

namespace App\Providers;

use App\Letter;
use App\Policies\LetterPolicy;
use App\Policies\UserPolicy;
use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        User::class => UserPolicy::class,
        Letter::class => LetterPolicy::class,
    ];

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

在下面的代码中,我检查用户

class LetterController extends Controller
{
protected $user;
public function __construct()
{
    $this->middleware(function ($request, $next){
       $this->user = Auth::user();
        return $next($request);
    });

}
public function edit(Letter $letter)
{
    if($this->user->can('update', $letter)){           
       //edit
    }
    else
        abort('403', 'Access Denied');
}

该代码在localhost中运行良好,但是在远程服务器上它报告了access denied错误。我在服务器上部署站点后创建了此策略,因此我使用代码

创建了路由/clear-cache
    Route::get('/clear-cache', function() {
        $exitCode = \Illuminate\Support\Facades\Artisan::call('cache:clear');
    });

在创建策略后清除缓存。但是它仍然报告403错误。有什么问题吗?

2 个答案:

答案 0 :(得分:2)

Fjarlaegur的答案是关键。我遇到了同样的问题:在localhost中没有问题,但是在生产服务器中,每一个授权都以某种方式失败了,这是由于比较运算符引起的。从===更改为==,一切都很好。

答案 1 :(得分:0)

我在COntroller中尝试了dd($this->user->id === $letter->user_id || $this->user->role_id===1 );,但返回了false。我尝试了dd($this->user->id == $letter->user_id || $this->user->role_id==1 );,它是true。现在可以用了,但我不知道为什么!