Laravel请求验证只允许用户id与登录的用户id相同



我需要检查规则(或授权)用户是否可以被授权删除他的评论。我该怎么做呢?这是我的规则

'user_id' => [
'required',
'exists:user,id',
],

我在这里检查用户是否存在,但我如何检查用户是否与登录的用户相同?

现在我在controller

中检查它
public function destroy(CommentDestroyRequest $request, Comment $comment)
{
$userId = Auth::id();
if ($comment->user_id !== $userId)
return response()->json(null, Response::HTTP_FORBIDDEN); 
}

但是我想移动它

问题上下文不正确。您正在尝试使用输入验证来授权用户。

;如果你想使用登录用户的id来创建一个新记录,你不需要从表单中发布它,只要使用$request->user()->idAuth::id()就可以了。确保始终有一个经过身份验证的用户;为该路由添加auth中间件(或控制器方法)。

另一方面,如果你想检查用户是否被授权做某事,你应该使用Laravel内置的授权服务。

要完成此操作,可以使用GatePolicy

文档如下:https://laravel.com/docs/8.x/authorization

假设你想确定一个用户是否被授权删除一个Comment,你可以通过写Gates

来做到这一点你可以在你的app/Providers/AuthServiceProvider.php文件的boot方法中定义gate;

// app/Providers/AuthServiceProvider.php
use AppModelsComment;
use AppModelsUser;
use IlluminateSupportFacadesGate;
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('delete-comment', function (User $user, Comment $comment) {
return $user->id === $comment->user_id;
});
}

现在您可以使用该门的名称-这里是delete-comment-来检查授权。

public function destroy(CommentDestroyRequest $request, Comment $comment)
{
if (Gate::denies('delete-comment', $comment)) abort(403);

// Authorization checked, you can do whatever you want
$comment->delete();
return redirect('/comments');
}

或者你可以在控制器中使用authorize;

public function destroy(CommentDestroyRequest $request, Comment $comment)
{
$this->authorize('delete-comment', $comment);

// Authorization checked, you can do whatever you want
$comment->delete();
return redirect('/comments');
}

这对你会有用的。

但是在Laravel中更方便的授权方式是策略。你一定要检查并考虑使用它们。

策略是围绕a组织授权逻辑的类特定的模型或资源。例如,如果您的应用程序是博客,你可能有一个AppModelsPost模型和相应的AppPoliciesPostPolicy授权用户进行创建等操作或者更新帖子

你也应该保存你的user_id在评论部分,这样你可以很容易地检测用户是否经过身份验证

最新更新