在搭建JWT生成token的时候,attempt(array) 总是返回false。原因在于生成token加密方式为Hasing。
JWT的搭建在此就不多说了。网上随便搜索就有了。此教程仅仅修改token密码的验证方式
创建验签方式:
<?php
namespace App\Helper\Hasher;
use Illuminate\Contracts\Hashing\Hasher;
class MD5Hasher implements Hasher
{
public function info($hashedValue)
{
// TODO: Implement info() method.
}
public function check($value, $hashedValue, array $options = [])
{
return $this->make($value) === $hashedValue;
}
public function needsRehash($hashedValue, array $options = [])
{
return false;
}
public function make($value, array $options = [])
{
$value = env('SALT', '').$value;
//自行对password 进行加密处理 目前又前端加密, 后端直接判断password是否一致即可
//return md5($value);
return $value;
}
}
创建provider.php
<?php
namespace App\Providers;
use App\Helper\Hasher\MD5Hasher;
use Illuminate\Support\ServiceProvider;
use Illuminate\Hashing\BcryptHasher;
class MD5HashServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('hash', function () {
return new BcryptHasher;
});
}
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->app->singleton('hash', function () {
//加密处理
return new MD5Hasher;
});
}
public function provides()
{
return ['hash'];
}
}
修改provider 方式,修改config/app.php
'providers' => [
/*
* Laravel Framework Service Providers...
*/
.....
//注释原本的加密方式
//Illuminate\Hashing\HashServiceProvider::class,
\App\Providers\MD5HashServiceProvider::class,
.....
],
生成token
public function login()
{
$token_info = [
'username' => $data['username'],
'password' => $data['password'],
];
if (! $token = auth('api')->attempt($token_info))
throw new ApiException("创建token 失败");
}
public function info()
{
$token_info = auth('api')->user();
}
|