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字段
\app\User.php
/** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password','api_token' ];
2.3 修改配置文件
\config\auth.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
\app\Http\Requests\BaseRequest.php
添加两个方法
/** * @return bool * 确定当前请求是否要求JSON。 */ public function wantsJson() { return true; } /** * @return bool * 确定当前请求是否可能期望JSON响应 */ public function expectsJson() { return true; }
2.5 配置接受和返回json
\public\index.php
$response = $kernel->handle( // $request = Illuminate\Http\Request::capture() $request = \App\Http\Requests\BaseRequest::capture() );
2.6 编写api认证代码
2.61 路由
\routes\api.php
Route::post('/register','Auth\ApiController@register'); Route::post('/login','Auth\ApiController@login'); Route::post('/refresh','Auth\ApiController@refresh'); Route::post('/logout','Auth\ApiController@logout');
2.62 控制器
php artisan make:controller Auth\ApiController
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\User; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Str; use App\Traits\AuthenticatesUsers; 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 register(Request $request) { $this->validator($request->all())->validate(); $api_token = Str::random(80); $data = array_merge($request->all(),compact('api_token')); $this->create($data); return compact('api_token'); } protected function validator(array $data) { return Validator::make($data,[ 'name'=>['required','string','max:255','unique:users'], 'password'=>['required','string','min:8','confirmed'] ]); } protected function create(array $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_verify(request('password'),$user->password)){ return response()->json(['error'=>'抱歉,账号名或密码错误'],403); } $api_token = Str::random(80); $user->update(['api_token'=>hash('sha256',$api_token)]); return compact('api_token'); } public function refresh() { $api_token = Str::random(80); 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授权码模式认证