从零开始系列-Laravel编写api服务接口:5.中间件验证JWT登陆

Laravel框架
458
0
0
2022-04-12
标签   Laravel授权

前言: 再第 3 章中介绍了如何使用多用户的jwt认证,下面讲讲怎么实现 jwt 多用户鉴权

  1. 路由文件

路由接口文件应该充分分组,按照系统的业务逻辑分成:

所有模块->不需要登录(比如通用的分类、图片上传等)

用户模块->不需要登录 (登录、注册、找回密码等)

用户模块->需要登录

管理员模块->不需要登录(比如登录、注册、找回密码等)

管理员模块->需要登录

闲话少叙,下面是路由代码 api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/ 

Route::get('/user', function (Request $request) {return ['asdf'];
});


// 配置dingo路由
$api = app('Dingo\Api\Routing\Router');

// 默认Accept application/prs.hospital.v1+json
$api->version('v1', ['namespace' => 'App\Http\Controllers\V1', 'middleware' => []], function ($api) {

    // 公共路由   
    $api->group(['as' => 'common', 'prefix' => 'common', 'namespace' => 'Common', 'middleware' => []], function ($api) {// 登录获取token   
        $api->post('authorization', 'AuthorizationController@store')->name('.authorizations.store');// 刷新token   
        $api->get('refresh_token', 'AuthorizationsController@refresh')->name('.authorizations.refresh');// 退出登录   
        $api->get('log_out', 'AuthorizationsController@logOut')->name('.authorizations.refresh');});

    //管理员后台接口   
    $api->group(['as' => 'admin', 'prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => []], function ($api) {//需要登录后的接口   
        $api->group(['middleware' => ['auth:admin']], function ($api) {
            $api->get('me','AdminsController@me');});});

    // 用户员接口   
    $api->group(['as' => 'user', 'prefix' => 'user', 'namespace' => 'User', 'middleware' => []], function ($api) {//需要登录后的接口   
        $api->group(['middleware' => ['auth:user']], function ($api) {
            $api->get('me','UsersController@me');});});
});

补上对应的控制器

php artisan make:controller V1/Admin/AdminsController

php artisan make:controller V1/User/UsersController

UsersController代码都一样这里只写AdminsController

<?php

namespace App\Http\Controllers\V1\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AdminsController extends Controller
{
  public function me(){
    return auth('admin')->user();
  }
}

访问接口:get http://homestead.test/api/admin/me

header里面加上刚才生成的token

Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9ob21lc3RlYWQudGVzdFwvYXBpXC9jb21tb25cL2F1dGhvcml6YXRpb24iLCJpYXQiOjE2MTAzNTM5MjUsImV4cCI6MTYxODEyOTkyNSwibmJmIjoxNjEwMzUzOTI1LCJqdGkiOiJLNW1ZenZsOEY3N1A0azl0Iiwic3ViIjoxLCJwcnYiOiJkZjg4M2RiOTdiZDA1ZWY4ZmY4NTA4MmQ2ODZjNDVlODMyZTU5M2E5In0.NYZKW2wbfMPAjLF-d-oA88OMrCNo8WHy7wAM_zhxlzU

访问结果:

{"id": 1,"name": "Helmer Graham","account": "38129","password": "$2y$10$rQ54Rh.FMPGWR8q9Oq8UUOCH4YYLurx2MPK/4aDgnh0yLh6Ow7sTa","created_at": "2021-01-08T09:33:56.000000Z","updated_at": "2021-01-08T09:33:56.000000Z"
}

别忘了要删除这一段(最新版本的laravel会默认走这里,旧版没这个跳转)

app\Http\Middleware\Authenticate.php

    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
protected function redirectTo($request){
//        if (! $request->expectsJson()) {
//            return route('login');
//        }
}

用户控制器也是一样控制器guard改一下就行了

return auth('user')->user();
// 下面写法同样有效
dump($request->user());
dump(auth('admin')->user());
dump(\Illuminate\Support\Facades\Auth::user());
dump(\Illuminate\Support\Facades\Auth::guard('admin')->user());

至此完成!是不是很简单。