1 原理
1.1 注册
用户注册后,随机生成长字符串作为token,原生的token返回给用户,哈希后的token存到数据库里
1.2 登录
用户使用账号密码登录成功,随机生成字符串作为token,原生的token返回给用户,哈希后的token存到数据库里
1.3 认证
将用户传来的原生的token经行哈希,然后取数据库中查找哈希后的token,找到了就认证成功,否则失败。
2 使用
2.1 users添加api_token字段
2.2 设置模型可操作api_token字段
appUser.php
/** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password','api_token' ];
2.3 修改配置文件
configauth.php
'defaults' => [ //'guard' => 'web', 'guard' => 'api', 'passwords' => 'users', ],
'api' => [ 'driver' => 'token', 'provider' => 'users', 'hash' => true, //用SHA-256算法哈希你的令牌 ],
2.4 设置所有请求和响应都是json格式
php artisan make:request BaseRequest
appHttpRequestsBaseRequest.php
添加两个方法
/** * @return bool * 确定当前请求是否要求JSON。 */ public function wantsJson) { return true; } /** * @return bool * 确定当前请求是否可能期望JSON响应 */ public function expectsJson) { return true; }
2.5 配置接受和返回json
publicindex.php
$response = $kernel->handle // $request = IlluminateHttpRequest::capture) $request = AppHttpRequestsBaseRequest::capture) );
2.6 编写api认证代码
2.61 路由
outesapi.php
Route::post'/register','AuthApiController@register'); Route::post'/login','AuthApiController@login'); Route::post'/refresh','AuthApiController@refresh'); Route::post'/logout','AuthApiController@logout');
2.62 控制器
php artisan make:controller AuthApiController
<?php namespace AppHttpControllersAuth; use AppHttpControllersController; use IlluminateHttpRequest; use AppUser; use IlluminateSupportFacadesValidator; use IlluminateSupportFacadesAuth; use IlluminateSupportStr; use AppTraitsAuthenticatesUsers; class ApiController extends Controller { // public function __construct) { $this->middleware'auth') ->except'login','register'); } /* * 由于我已经在Traits里修改了认证字段 所以这里不需要。 * https://www.cnblogs.com/polax/p/14656132.html * protected function username) { return 'name'; } */ use AuthenticatesUsers; public function registerRequest $request) { $this->validator$request->all))->validate); $api_token = Str::random80); $data = array_merge$request->all),compact'api_token')); $this->create$data); return compact'api_token'); } protected function validatorarray $data) { return Validator::make$data,[ 'name'=>['required','string','max:255','unique:users'], 'password'=>['required','string','min:8','confirmed'] ]); } protected function createarray $data) { return User::forceCreate[ 'name' =>$data['name'], //'email' =>$data['email'], 'password' =>password_hash$data['password'],PASSWORD_DEFAULT), 'api_token' =>hash'sha256',$data['api_token']) ]); } public function logout) { Auth::user)->update['api_token'=>null]); return ['message'=>'退出登录成功']; } public function login) { $user = User::where$this->username),request$this->username))) ->firstOrFail); if !password_verifyrequest'password'),$user->password)){ return response)->json['error'=>'抱歉,账号名或密码错误'],403); } $api_token = Str::random80); $user->update['api_token'=>hash'sha256',$api_token)]); return compact'api_token'); } public function refresh) { $api_token = Str::random80); Auth::user)->update['api_token'=>hash'sha256',$api_token)]); return compact'api_token'); } }
3 测试
3.1 注册
3.2 登录
3.3 刷新token
传入的token是未哈希过的
3.4 登出
4 其他认证
Laravel 7 用户认证 Auth ——传统web认证
Laravel 7 用户认证 Auth ——Passport密码模式认证
Laravel 7 用户认证 Auth ——Passport授权码模式认证