Framework: authorizeResource() does not work. Again.

Created on 10 Jan 2018  路  5Comments  路  Source: laravel/framework

  • Laravel Version: 5.5.28
  • PHP Version: 7.1
  • Database Driver & Version: MySQL 5.7

Description:

Hi. I have a basic resource controller and I want to apply policy to it. $this->authorize() works perfectly, but there are too many methods to apply this to each one. So I found a method called authorizeResource(). But is doesn't work. It seems to me that it is my fault, but by the way I can't find a mistake..

My code snippets: ("..." means other unnecessary methods, that are similar)

EmailListController:

....
public function __construct()
{
    $this->authorizeResource(EmailList::class);
}
...
/**
 * Display the specified resource.
 *
 * @param  EmailList $list
 * @return \Illuminate\Http\Response
 */
public function show(EmailList $list)
{
    //$this->authorize('view', $list);   This worked perfectly
    return view('dispatch.lists.exact')->with('list', $list);
}
...

EmailListPolicy:

....
/**
 * Determine whether the user can view the emailList.
 *
 * @param  \App\User  $user
 * @param  \App\EmailList  $list
 * @return mixed
 */
public function view(User $user, EmailList $list)
{
    return $user->id === $list->user_id;
}
....

EmailList model:

...
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'user_id', 'list_name', 'list_key',
];
...

Resource route:

Route::prefix('dispatch')->group(function () {
    Route::resource('lists', 'Dispatch\EmailListsController');
}

Everything seems to be correct, but I get 'This action is unauthorized.'

Most helpful comment

Excuse me.. what exactly did you fill in in your parameter? I added the FQN model .
$this->authorizeResource(Role::class, Role::class);

However, when adding multiple arguments i get exactly the same problem as you have.

All 5 comments

Fixed. It is important to set "parameter" name.

Be aware that authorizeResource will not work out of the box for the index method.

See https://github.com/laravel/ideas/issues/772 for info and workarounds

Excuse me.. what exactly did you fill in in your parameter? I added the FQN model .
$this->authorizeResource(Role::class, Role::class);

However, when adding multiple arguments i get exactly the same problem as you have.

@renalpha to pass multiple parameters i do:

public function store() {
    $this->authorize('create', [Model1::class, Model2::class]);
}

Found you a way to do the same with $this->authorizeResource($model, $parameter = null, array $options = [], $request = null)?

I found that getting the paramater correct for authorizeResource was very fiddly. A few notes:

  1. Must be in lower case, even if the parameter is declared in upper case in the model
  2. Must be a string (without variable defining $) and in single tick quote marks

For example:

$this->authorizeResource(Model::class, 'parameter');

Was this page helpful?
0 / 5 - 0 ratings