扩展请求类的属性为空 - Laravel(英语:Laravel)



我已经为Google 2fa创建了一个自己的请求,名为ValidateSecretRequest。但我只得到空属性。

作为附加信息:我遵循了 https://www.sitepoint.com/2fa-in-laravel-with-google-authenticator-get-secure/教程

在 authenticate(( 方法之后,LoginController 执行 postValidateToken(( 方法。为了测试,我只实现了请求输出。

登录控制器

public function postValidateToken(ValidateSecretRequest $request) {
      echo '<pre>'; print_r($request); echo '</pre>';
}

请求类

首先,我认为扩展的请求有误?其实这样应该对吧?

<?php
namespace AppHttpRequests;
use Cache;
use Crypt;
use Google2FA;
use AppUser;
use IlluminateValidationFactory as ValidatonFactory;
use IlluminateHttpRequest;
class ValidateSecretRequest extends Request {
   /**
    *
    * @var AppUser
    */
   private $user;
   public $totp;
   /**
    * Create a new FormRequest instance.
    *
    * @param IlluminateValidationFactory $factory
    * @return void
    */
   public function __construct(ValidatonFactory $factory) {
      $factory->extend(
         'valid_token',
         function ($attribute, $value, $parameters, $validator) {
            $secret = Crypt::decrypt($this->user->google2fa_secret);
            return Google2FA::verifyKey($secret, $value);
         },
         'Not a valid token'
      );
      $factory->extend(
         'used_token',
         function ($attribute, $value, $parameters, $validator) {
            $key = $this->user->id . ':' . $value;
            return !Cache::has($key);
         },
         'Cannot reuse token'
      );
   }
   /**
    * Determine if the user is authorized to make this request.
    *
    * @return bool
    */
   public function authorize() {
      try {
         $this->user = User::findOrFail(
            session('2fa:user:id')
         );
      } catch (Exception $exc) {
         return false;
      }
      return true;
   }
   /**
    * Get the validation rules that apply to the request.
    *
    * @return array
    */
   public function rules() {
      return [
         'totp' => 'bail|required|digits:6|valid_token|used_token',
      ];
   }
}

但是函数postValidateToken((返回一个空数组。

AppHttpRequestsValidateSecretRequest Object
(
    [user:AppHttpRequestsValidateSecretRequest:private] => 
    [totp] => 
    [json:protected] => 
    [convertedFiles:protected] => 
    [userResolver:protected] => 
    [routeResolver:protected] => 
    [attributes] => 
    [request] => 
    [query] => 
    [server] => 
    ...
    [session:protected] => 
    [locale:protected] => 
    [defaultLocale:protected] => en
    [isHostValid:SymfonyComponentHttpFoundationRequest:private] => 1
    [isForwardedValid:SymfonyComponentHttpFoundationRequest:private] => 1
)

找到了解决方案:

您必须使用表单请求而不是请求

use IlluminateFoundationHttpFormRequest;

相关内容

最新更新