laravel5.7 前后端分离开发 实现基于API请求的token认证
转载自:https://blog.csdn.net/wei_yalin/article/details/86559513
最近在学习前后端分离开发,发现 在laravel中实现前后台分离是无法无法使用 CSRF Token 认证的。因为 web 请求的用户认证是通过Session和客户端Cookie的实现的,而前后端分离的应用无法通过API请求将Cookie 和 CSRF Token 从前端传递到后端,但是还有一种解决方法,就是使用laravel自带的 API token认证。
第一步:用户表添加api_token字段
1、可以通过数据迁移的方式添加,像这样:
php artisan make:migration --table=用户表名 add_api_token
然后编写这个迁移文件,文件位于 database/migration 中
- class AddApiToken extends Migration
- {
- /**
- * Run the migrations.
- *
- * @return void
- */
- public function up()
- {
- Schema::table('用户表名', function (Blueprint $table) {
- $table->string('api_token', 200)->unique()->nullable();
- });
- }
-
- /**
- * Reverse the migrations.
- *
- * @return void
- */
- public function down()
- {
- Schema::table('用户表名', function (Blueprint $table) {
- $table->dropColumn(['api_token']);
- });
- }
- }
然后执行迁移命令
php artisan migrate
2、或者像我这样,直接在数据库用户表中添加,O(∩_∩)O哈哈~
因为 varchar 存储的是变长数据,也就是数据的真实长度,所以不要吝啬可以给长度设大点。
第二步、添加认证服务方
我是多表认证,每个用户角色有一张表,所以需要添加认证服务方,在 config/auth.php 中添加。一般使用已经默认的 api 认证方就好,
第三步、给用户模型添加生成api_token方法
- /**
- * 更新token
- * @return mixed|string
- */
- public function generateToken() {
- $this->api_token = str_random(128);
- $this->save();
-
- return $this->api_token;
- }
第四步、在控制器中添加登录方法
这是我的登录认证,是基于多表的用户认证,我是个小菜菜,细节就不给你们看了,怕你们喷我⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄。总之是在登陆验证成功之后,生成api_token并返回就可以了。
第五步、给路由添加认证中间件
在 api.php 添加如下路由,login 不需要守卫,给 logout 和 其他需要认证的路由添加守卫就可以了(auth:admin , 对应上面的admin用户)
- Route::any('unAuth', function () {
- return responseToJson(1,'未认证或认证失败');
- })->name('unAuth');
-
- Route::prefix('admin')->namespace('Admin')->group(function() {
- Route::post('login', 'LoginController@login');
- Route::middleware('auth:admin')->group(function() {
- Route::post('logout', 'LoginController@logout');
- Route::get('getMenu', 'MenuController@getMenu');
- });
- });
使用的是auth中间件,默认的路由我没有O(∩_∩)O,所以需要进行修改。
修改中间件 Authenticate.php , 位于 app/Http/Middleware/Authenticate.php 。
- class Authenticate extends Middleware
- {
- /**
- * Get the path the user should be redirected to when they are not authenticated.
- *
- * @param \Illuminate\Http\Request $request
- * @return string
- */
- protected function redirectTo($request)
- {
- if (! $request->expectsJson()) {
- return route('unAuth');
- }
- }
- }
现在就已经好了,在登陆之后会返回 api_token ,然后请求其他路由的时候把 api_token 当参数传过来。这样当请求需要认证的路由的时候如果没有 api_token 或者 api_token 错误,就会跳转到 unAuth 路由,然后返回定义好的提示信息。
第六步、退出时清除 token
- public function logout()
- {
- $user = Auth::guard('admin')->user();
-
- if ($user) {
- $user->api_token = null;
- $user->save();
- }
-
- return responseToJson(0,'退出成功');
- }
还可以写个中间件,每隔一段时间更新一下 api_token 值,同时前端也要更新 api_token 。我写的也不是多好,可以看一下
- /**
- * Handle an incoming request.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @param string|null $guard
- * @return mixed
- */
- public function handle($request, Closure $next, $guard)
- {
- $response = $next($request);
-
- //验证token是否过期
- $user = Auth::guard($guard)->user();
- if (isTimeGreater($user->updated_token_at)){
- $response->header("api_token", $user->generateToken());
- }
-
- return $response;
- }