Laravel 5.4 授权 - 使用 can 方法失败
Laravel 5.4 Authorization - using can method unsuccessfully
我正在使用 Laravel 5.4 策略来管理用户能力。
目标是使用 'can' 方法删除 post。
即使销毁方法('DELETE')已经运行,它也没有成功通过if语句删除post。
我已将 PostPolicy.php 中的 return 值更改为 'true' 以移除任何其他变量。
PostPolicy.php:
public function delete(User $user, Post $post)
{
return true;
}
PostsController.php:
public function destroy($id)
{
$post = Post::findOrFail($id);
if ($user->can('delete', $post)) {
$post->delete();
}
return response()->json($post);
}
您没有获得用户实例。如果要检查经过身份验证的用户的权限,请使用 auth()->user()
object:
if (auth()->user()->can('delete', $post)) {
$post->delete();
}
或使用authorize()
方法:
$this->authorize('delete', $post);
$post->delete();
In addition to helpful methods provided to the User
model, Laravel provides a helpful authorize
method to any of your controllers which extend the App\Http\Controllers\Controller
base class. Like the can method, this method accepts the name of the action you wish to authorize and the relevant model. If the action is not authorized, the authorize
method will throw an Illuminate\Auth\Access\AuthorizationException
, which the default Laravel exception handler will convert to an HTTP response with a 403
status code
https://laravel.com/docs/5.4/authorization#via-controller-helpers
问题出在我的 AuthServiceProvider.php 文件中。
我没有包括以下 类:
use App\Post;
use App\Policies\PostPolicy;
我正在使用 Laravel 5.4 策略来管理用户能力。
目标是使用 'can' 方法删除 post。 即使销毁方法('DELETE')已经运行,它也没有成功通过if语句删除post。 我已将 PostPolicy.php 中的 return 值更改为 'true' 以移除任何其他变量。
PostPolicy.php:
public function delete(User $user, Post $post)
{
return true;
}
PostsController.php:
public function destroy($id)
{
$post = Post::findOrFail($id);
if ($user->can('delete', $post)) {
$post->delete();
}
return response()->json($post);
}
您没有获得用户实例。如果要检查经过身份验证的用户的权限,请使用 auth()->user()
object:
if (auth()->user()->can('delete', $post)) {
$post->delete();
}
或使用authorize()
方法:
$this->authorize('delete', $post);
$post->delete();
In addition to helpful methods provided to the
User
model, Laravel provides a helpfulauthorize
method to any of your controllers which extend theApp\Http\Controllers\Controller
base class. Like the can method, this method accepts the name of the action you wish to authorize and the relevant model. If the action is not authorized, theauthorize
method will throw anIlluminate\Auth\Access\AuthorizationException
, which the default Laravel exception handler will convert to an HTTP response with a403
status code
https://laravel.com/docs/5.4/authorization#via-controller-helpers
问题出在我的 AuthServiceProvider.php 文件中。 我没有包括以下 类:
use App\Post;
use App\Policies\PostPolicy;