【问题标题】:How to get Laravel Auth Policies working with API Controller, and Form Requests如何让 Laravel Auth Policies 与 API Controller 和 Form Requests 一起工作
【发布时间】:2023-02-20 11:06:43
【问题描述】:

我有一个样板 Laravel 应用程序,使用 cli 命令 php artisan make:model Post -a --api 生成一个模型来制作一个 API 控制器,带有表单请求和策略。

Laravel Policy Authorisation 文档似乎没有明确说明如何处理 Policy 和 FormRequest。我是否在 FormRequest 中调用策略类?或者忽略存储/更新策略?

如何将身份验证策略与 FormRequests 一起用于我的 API 控制器?

版本

Laravel 9

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    文档没有说清楚,张贴以防其他人遇到困难。用户模型、UserPolicy 和 UserController 的示例。

    第一的,在AuthServiceProvider中添加Policy类。

    AppProvidersAuthServiceProvider
    
        /**
         * The policy mappings for the application.
         *
         * @var array<class-string, class-string>
         */
        protected $policies = [
            User::class => UserPolicy::class,
        ];
    

    第二,在控制器中使用 authorizeResources 将策略自动映射到 api 控制器。请参阅here 了解策略 -> 控制器映射到的内容

    // AppHttpControllersUserController
    
    use AppModelsUser;
    use IlluminateHttpRequest;
    use AppHttpRequestsStoreUserRequest;
    use AppHttpRequestsUpdateUserRequest;
    
    class UserController extends Controller
    {
        /**
         * Create the controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            // Sets up user policy for this controller
            $this->authorizeResource(User::class, 'user');
        }
    ...
    }
    

    最后的,删除FormRequests 的授权部分

    // AppHttpRequestsUpdateUserRequest
    
    class UpdateUserRequest extends FormRequest
    {
        // DELETE the auth part below, otherwise it'd mess up using policies. 
        // I'm pretty sure this takes precedence over policies
        /**
         * Determine if the user is authorized to make this request.
         *
         * @return bool
         */
        //public function authorize()
        //{
            //return true;
        //}
    }
    

    现在,在 UserPolicy 中设置的策略将用作用户控制器的身份验证守卫。

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 1970-01-01
      • 2015-01-01
      • 2020-04-25
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      相关资源
      最近更新 更多