I am writing an application in laravel and vue. I have done authentication on sanctum and breeze. She works. I wanted to authorize user actions so that he could create content on the site if he has the appropriate role. I wrote the policy:
class NftPolicy
{
public function create(User $user): bool
{
// return $user->role === 'admin' || $user->role === 'author';
return true;
}
I registered it in the App Service Provider in boot:
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
//
}
public function boot(): void
{
Gate::policy(Nft::class, NftPolicy::class);
ResetPassword::createUrlUsing(function (object $notifiable, string $token) {
return config('app.frontend_url')."/password-reset/$token?email={$notifiable->getEmailForPasswordReset()}";
});
}
}
I tried to use it in the controller (do not pay attention to the current code in it, I tried many options, it still did not work):
class StoreNftController extends Controller
{
public function __invoke(StoreRequest $request)
{
if (Gate::denies('create', Nft::class)) {
abort(403, 'Unauthorized action.');
}
// Gate::authorize('create', Nft::class);
$data = $request->validated();
$data['author_id'] = auth()->id();
$nft = Nft::create($data);
return response()->json($nft, 201);
}
}
I always get a 403 error when I try to perform an action. No matter how I change something, the error still remains. Although I checked that the user is authenticated, he gets to the client from the server and on the server if you try to output him to laravel.log, the data will be there, but still the error is constant.
I have seen that some people say that you need to put the policy in the folder with models, in older information the policy was registered in AuthServiceProvider, but in version 11 there is no such thing. Maybe I didn’t finish something somewhere..
I hope for help.
2