bla*_*azR 1 php laravel laravel-5.4
我正在使用laravel 5.4构建API,在该API中,如果用户验证了密码重置,我会通过电子邮件向用户发送令牌,该令牌在重置密码之前由用户提供。当前发送的令牌有64个字符,并且太大而无法被用户抓取,我不确定laravel是否配置为令牌自定义长度?
解决方案有些棘手,请尝试尽可能清楚地解释该过程:
步骤1-扩展标准DatabaseTokenRepository
创建一个扩展类Illuminate\Auth\Passwords\DatabaseTokenRepository以定义新的令牌创建策略。
<?php
namespace App\Auth\Passwords;
use Illuminate\Auth\Passwords\DatabaseTokenRepository;
class CustomDatabaseTokenRepository extends DatabaseTokenRepository
{
// Overrides the standard token creation function
public function createNewToken()
{
retrun substr(parent::createNewToken(), 0, 30);
}
}
Run Code Online (Sandbox Code Playgroud)
我刚刚将Laravel生成的令牌缩减为30个字符,可以随意实现自己的令牌生成例程。
步骤2-扩展标准的PasswordBrokerManager
现在,您必须告诉PasswordBrokerManager,使用令牌存储库而不是标准存储库。为此,您必须扩展类Illuminate\Auth\Passwords\PasswordBrokerManager。
<?php
namespace App\Auth\Passwords;
use Illuminate\Auth\Passwords\PasswordBrokerManager;
class CustomPasswordBrokerManager extends PasswordBrokerManager
{
// Override the createTokenRepository function to return your
// custom token repository instead of the standard one
protected function createTokenRepository(array $config)
{
$key = $this->app['config']['app.key'];
if (Str::startsWith($key, 'base64:')) {
$key = base64_decode(substr($key, 7));
}
$connection = isset($config['connection']) ? $config['connection'] : null;
return new CustomDatabaseTokenRepository(
$this->app['db']->connection($connection),
$this->app['hash'],
$config['table'],
$key,
$config['expire']
);
}
}
Run Code Online (Sandbox Code Playgroud)
步骤3-扩展标准 PasswordResetServiceProvider
现在,您必须扩展标准Illuminate\Auth\Passwords\PasswordResetServiceProvider才能告诉Laravel实例化您的代码CustomPasswordBrokerManager。
<?php
namespace App\Auth\Passwords;
use Illuminate\Auth\Passwords\PasswordResetServiceProvider;
class CustomPasswordResetServiceProvider extends PasswordResetServiceProvider
{
// Override the method registerPasswordBroker
// in order to specify your customized manager
protected function registerPasswordBroker()
{
$this->app->singleton('auth.password', function ($app) {
return new CustomPasswordBrokerManager($app);
});
$this->app->bind('auth.password.broker', function ($app) {
return $app->make('auth.password')->broker();
});
}
}
Run Code Online (Sandbox Code Playgroud)
STEP 4 - Final step, replace the provider in config/app.php
Comment out the following line in your config/app.php files under the providers key:
// Illuminate\Auth\Password\PasswordResetServiceProvider::class,
And add the following line just below:
App\Auth\Passwords\CustomPasswordResetServiceProvider::class,
CONSIDERATIONS
Be careful when doing such things, the token is defined as hash_hmac('sha256', Str::random(40), $this->hashKey) where $this->hasKey is env('APP_KEY). This is used to ensure that no collision will occur when generating password reset tokens. I suggest you to investigate a secure method to reduce your token length securely.
| 归档时间: |
|
| 查看次数: |
1516 次 |
| 最近记录: |