从字符串生成一个令牌并检查它


Generate a token from string and check it

我有一个多种产品类型的表单。每种类型由一个select选项加载。

像这样:

<select name="name">
  <option value="product_1"> product one </option>
  <option value="product_2"> product two </option>
</select>

每个产品类型都有不同的投入。当select变化触发一个ajax请求加载引用inputs

为了在后端中进行数据验证,我必须使用option值来知道提交的产品类型。

现在,漏洞:

  1. 用户选择并填写一些产品类型
  2. 用户故意将option标签的当前值(在浏览器上)更改为另一个有效值
  3. 用户向服务器发送不一致的数据

显然,验证这个不是不可能的,但是有点无聊。

为方便起见,对于每种产品类型,我放置一个input[type=hidden]与一个"令牌"(哈希)作为value属性。

实际上,"令牌"只不过是(变通)Hash::make( $selected_option_value )

参见Laravel网站上的哈希。

现在,当产品提交时,只需检查Hash::check( $selected_option_value, $selected_option_value_hash)是否为true,我对产品类型有"确定"

当然这个变量名不是真的

但是这样做,bcrypt (Hash::make())似乎不是个好主意。

所以,我有一些问题:

  1. 如何从字符串生成令牌,并将其检查为password_hashpassword_verify后?

  2. 或者有更好的方法来解决这个问题?

我个人会使用请求来验证这一点。

首先使用artisan命令

php artisan make:request MyRequest

然后在你的请求中使用

<?php namespace App'Http'Requests;
use App'Http'Requests'Request;
class MyRequest extends Request {
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return Auth::check();
    }
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'exists:products,name'
        ];
    }
}
控制器中的

确保使用了请求。我喜欢对这个

使用依赖注入
public function myFunction(MyRequest $request)
{
    /*Stuff */
}

确保在控制器的顶部声明它

use App'Http'Requests'MyRequest;

http://laravel.com/docs/5.1/validation规则存在