• Laravel6.0 使用 Jwt-auth 实现多用户接口认证


    后台管理员认证 (admins 表)

    首先创建数据库和表 (admins),在 routes/api.php 中,写上如下路由并创建对应控制器和方法。

    Route::namespace('Api')->group(function () {
        /***
         * 管理员后台接口路由
         */
        Route::prefix('admin')->namespace('Admin')->group(function () {
            Route::post('register', 'AdminController@register');
            Route::post('login', 'AdminController@login');
        });
        Route::prefix('admin')->namespace('Admin')->group(function () {
            Route::get('/', 'HomeController@index'); //后台首页
        });
    });

    1、安装 jwt-auth

    composer require tymon/jwt-auth:dev-develop

    2、在 config/app.php 中注册服务提供者

    TymonJWTAuthProvidersLaravelServiceProvider::class,

    3、生成配置文件

    php artisan vendor:publish --provider="TymonJWTAuthProvidersLaravelServiceProvider"

    此命令会在 config 目录下生成一个 jwt.php 配置文件

    4、生成密钥

    php artisan jwt:secret

    此命令会在你的 .env 文件中新增一行 JWT_SECRET=secret

    5、创建 admins 表迁移文件

    php artisan make:migration create_admins_table

    添加如下代码:

    public function up()
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    执行迁移:

    php artisan migrate

    此时查看数据库,对应的 admins 表已生成。

    6、创建模型

    由于我们这里后台管理员设置的是 admins 表,所以需创建对应模型,执行如下命令:

    php artisan make:model Models/Admin

    里面添加如下代码:

    <?php
    
    namespace AppModels;
    
    use TymonJWTAuthContractsJWTSubject;
    use IlluminateNotificationsNotifiable;
    use IlluminateFoundationAuthUser as Authenticatable;
    
    class Admin extends Authenticatable implements JWTSubject
    {
        use Notifiable;
    
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'name', 'email', 'password',
        ];
    
        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];
    
        /**
         * The attributes that should be cast to native types.
         *
         * @var array
         */
        protected $casts = [
            'email_verified_at' => 'datetime',
        ];
    
        public function getJWTIdentifier()
        {
            return $this->getKey();
        }
    
        public function getJWTCustomClaims()
        {
            return [];
        }
    }

    7、配置 Auth guard

    在 config/auth.php 文件中,添加 guard 和 Providers,代码如下:

    'admins' => [
        'driver'   => 'jwt',
        'provider' => 'admins'
    ]
    
    *************************
    
    'admins' => [
        'driver' => 'eloquent',
        'model' => AppModelsAdmin::class,
    ]

    8、在 AdminController 中添加如下代码:

    <?php
    
    namespace AppHttpControllersApiAdmin;
    
    use IlluminateHttpRequest;
    use AppHttpControllersController;
    use AppModelsAdmin;
    use Hash;
    
    class AdminController extends Controller
    {
        public function __construct()
        {
            $this->middleware('auth:admins', ['except' => ['register', 'login']]);
        }
    
        /***
         * 后台管理员注册
         * @param Request $request
         */
        public function register(Request $request)
        {
            $name = $request->name;
            $email = $request->email;
            $password = $request->password;
            $check_password = $request->check_password;
    
            if (!$name || !$password) {
                return response()->json(['success' => false, 'message' => '用户名、邮箱或密码必填!']);
            }
    
            $pattern = "/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,})$/";
            if (!preg_match($pattern, $email)) {
                return response()->json(['success' => false, 'message' => '邮箱格式不正确!']);
            }
    
            if ($check_password != $password) {
                return response()->json(['success' => false, 'message' => '两次密码输入不一致!']);
            }
    
            $admin = Admin::where('name', $name)->first();
            if ($admin) {
                return response()->json(['success' => false, 'message' => '用户名已被注册!']);
            }
    
            $password = Hash::make($password);
            $admin = Admin::create([
                'name' => $name,
                'email' => $email,
                'password' => $password
            ]);
    
            return response()->json(['success' => true, 'message' => '注册成功!', 'admin' => $admin]);
        }
    
        /***
         * 后台管理员登录
         * @param Request $request
         */
        public function login(Request $request)
        {
            $email = $request->email;
            $password = $request->password;
    
            if (!$email || !$password) {
                return response()->json(['success' => false, 'message' => '邮箱或密码填写错误!']);
            }
    
            $admin = Admin::where('email', $email)->first();
            if (!$admin) {
                return response()->json(['success' => false, 'message' => '此邮箱不存在!']);
            }
    
            if (!Hash::check($password, $admin->password)) {
                return response()->json(['success' => false, 'message' => '密码填写错误!']);
            }
    
            $credentials = request(['email', 'password']);
            if (!$token = auth('admins')->attempt($credentials)) {
                return response()->json(['error' => 'Unauthorized'], 401);
            }
    
            return $this->respondWithToken($token);
        }
    
        /**
         * Log the admin out (Invalidate the token).
         *
         * @return IlluminateHttpJsonResponse
         */
        public function logout()
        {
            auth()->logout();
    
            return response()->json(['message' => 'Successfully logged out']);
        }
    
        /**
         * Refresh a token.
         *
         * @return IlluminateHttpJsonResponse
         */
        public function refresh()
        {
            return $this->respondWithToken(auth('admins')->refresh());
        }
    
        /**
         * Get the token array structure.
         *
         * @param string $token
         *
         * @return IlluminateHttpJsonResponse
         */
        protected function respondWithToken($token)
        {
            return response()->json([
                'access_token' => $token,
                'token_type' => 'Bearer',
                'expires_in' => auth('admins')->factory()->getTTL() * 60
            ]);
        }
    }

    测试:

    先注册一个后台账号,在 postman 中,如图所示:

     

    9、使用中间件,修改之前的路由如下:

    Route::namespace('Api')->group(function () {
        /***
         * 管理员后台接口路由
         */
        Route::prefix('admin')->namespace('Admin')->group(function () {
            Route::post('register', 'AdminController@register');
            Route::post('login', 'AdminController@login');
        });
        Route::prefix('admin')->namespace('Admin')->middleware('auth:admins')->group(function () {
            Route::get('/', 'HomeController@index'); //后台首页
        });
    });

    测试:

    实现登录,在 postman 中,如图所示:

     

    12、获取管理员信息,在后台首页控制器中写入如下代码:

    public function index()
    {
        return response()->json(auth('admins')->user());
    }
     

    至此,后台接口认证已完成!

     

    商户后台认证 (merchants 表)

    这里的商户后台认证其实是重复上面的步骤,只是换了一张表而已,所以自行完成!

     

    小程序前端用户认证 (users 表)

    1、在 api.php 中添加路由并创建对应控制器和方法,users 表增加字段 openid

     /***
     * 小程序用户认证接口路由
     */
    Route::any('/auth', 'MiniController@auth');

    2、在 config/auth.php 文件中,修改 guard 里面的 api 那栏,代码如下:

    'users' => [
        'driver' => 'jwt',
        'provider' => 'users',
        'hash' => false,
    ],

    3、修改模型 User.php 代码如下:

    <?php
    
    namespace App;
    
    use TymonJWTAuthContractsJWTSubject;
    use IlluminateNotificationsNotifiable;
    use IlluminateFoundationAuthUser as Authenticatable;
    
    class User extends Authenticatable implements JWTSubject
    {
        use Notifiable;
    
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'name', 'email', 'password', 'openid'
        ];
    
        /**
         * Get the identifier that will be stored in the subject claim of the JWT.
         *
         * @return mixed
         */
        public function getJWTIdentifier()
        {
            return $this->getKey();
        }
    
        /**
         * Return a key value array, containing any custom claims to be added to the JWT.
         *
         * @return array
         */
        public function getJWTCustomClaims()
        {
            return [];
        }
    }

    4、使用中间件,修改之前的路由如下:

    /***
     * 小程序用户认证接口路由
     */
    Route::any('/auth', 'MiniController@auth');
    
    Route::middleware('auth:users')->group(function () {
        Route::get('/', 'HomeController@index'); //首页接口
    });

    5、安装 easyWeChat 第三方包

    composer require "overtrue/laravel-wechat:~5.0"  #安装包文件
    php artisan vendor:publish --provider="OvertrueLaravelWeChatServiceProvider"  #生成配置文件

    打开配置文件 wechat.php 里面的小程序配置和支付配置,在 .env 文件中配置支付的相关参数,如下:

    WECHAT_MINI_PROGRAM_APPID=*******
    WECHAT_MINI_PROGRAM_SECRET=*******
    
    WECHAT_PAYMENT_MCH_ID=*******
    WECHAT_PAYMENT_APPID=*******
    WECHAT_PAYMENT_KEY=*******

    6、在 MiniController 控制器中添加如下代码:

    <?php
    
    namespace AppHttpControllersApi;
    
    use IlluminateHttpRequest;
    use AppHttpControllersController;
    use AppUser;
    use JWTAuth;
    use EasyWeChat;
    use Auth;
    
    class MiniController extends Controller
    {
        public function auth(Request $request)
        {
            $app = EasyWeChat::miniProgram();
            $session = $app->auth->session($request->code);
            $openid = $session['openid'];
    //        return $openid;
            //用openid查询数据库,是否已经有了,没有就创建。
            $user = User::firstOrCreate(compact('openid'));
    
            //生成token
            $token = JWTAuth::fromUser($user);
            return response()->json(['token' => 'Bearer ' . $token]);
        }
    }

    7、创建一个小程序测试项目,在 app.js 中,刷出 code。然后 postman 测试如图:

     

    8、最后一步获取小程序用户 id。在首页接口控制器中写入如下代码,用来打印小程序用户的 openid

    public function index()
    {
        return response()->json(auth('users')->user()->openid);
    }
     
     
  • 相关阅读:
    Python-按指定列排序、斜着遍历
    牛客-SQL-刷题(下)
    特征工程之离散变量处理
    python 原生列表删除元素方法总结
    sklearn进行归一化
    Keras安装与测试遇到的坑
    常用机器学习算法优缺点及应用汇总
    特征工程
    机器学习模型评估指标总结
    pyecharts多图表同一页显示
  • 原文地址:https://www.cnblogs.com/sweetsunnyflower/p/11655747.html
Copyright © 2020-2023  润新知