05创建laravel5.8前后台api项目--jwt前台后台账号分离

安装jwt-auth

官方安装教程点击此处,我想要实现前台affiliate用户生成token跟后台admin用户生成token互不影响,首先创建两张表:执行命令php artisan make:model Affiliate -a 和 php artisan make:model Admin -a

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAffiliatesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // php artisan make:model Affiliate -a 生成数据库迁移脚本
        Schema::create('affiliates', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email', 32);
            $table->string('password', 128);
            $table->tinyInteger('status');
            $table->timestamps();
        });
    }
}
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAffiliatesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // php artisan make:model Affiliate -a 生成数据库迁移脚本
        Schema::create('affiliates', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email', 32);
            $table->string('password', 128);
            $table->tinyInteger('status');
            $table->timestamps();
        });
    }

}

配置jwt-auth

官方快速使用教程点击此处,推荐先撸一遍官网代码,然后尝试实践这个前后台账号分离的教程。

第一步:修改App\Models\Affiliate model文件

<?php

namespace App\Models;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Affiliate extends Authenticatable implements JWTSubject
{
    use Notifiable;

     /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password'
    ];

    // Rest omitted for brevity

    /**
     * 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 [];
    }
}

第二步:修改config/auth.php 配置了两个守卫中间件,想在路由使用frontend则需要指定auth:frontend(见第三步)

<?php

return [
    'defaults' => [
        'guard' => 'frontend',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'frontend' => [
            'driver' => 'jwt',
            'provider' => 'affiliate',
        ],

        'backend' => [
            'driver' => 'jwt',
            'provider' => 'admin',
        ],
    ],

    'providers' => [
        'affiliate' => [
            'driver' => 'eloquent',
            'model' => App\Models\Affiliate::class,
        ],

        'admin' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],

    ],
];

第三步:修改routes\local\frontend.php,第一个路由组不需要校验登录,第二个路由组需要走auth:frontend登录

<?php
// affiliate前台用户路由

Route::namespace('Frontend')->group(function(){

    Route::group(['prefix' => 'affiliate'], function () {
        // 用户登录
        Route::post('login', 'AffiliateController@login');
        // 用户注册
        Route::post('register', 'AffiliateController@register');
        // 发重置密码邮件
        Route::post('password/email', 'AffiliateController@password_email');

        // 重置密码
        Route::post('password/reset', 'AffiliateController@password_reset');
    });
    
});


Route::group(['namespace' => 'Frontend', 'middleware' => ['auth:frontend']], function(){
    Route::group(['prefix' => 'affiliate'], function () {
        // 验证token
        Route::post('me', 'AffiliateController@me');
        // 用户登出
        Route::post('logout', 'AffiliateController@logout');
        // 修改密码
        Route::post('password/update', 'AffiliateController@password_update');
    });
});

第四步:修改App\Http\Controllers\Frontend\AffiliateController

<?php

namespace App\Http\Controllers\Frontend;
use App\Http\Controllers\Controller;

use App\Models\Affiliate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AffiliateController extends Controller
{
    // 注册
    public function register()
    {
        $email = request()->input('email');
        $password = Hash::make(request()->input('password'));
        $ret = Affiliate::where('email', $email)->first();
        if($ret) return response()->json(['error' => 'email exist'], 500);
        
        Affiliate::create(['email' => $email, 'password'=>$password]);
        return response()->json(['success' => 'registered successfully'], 200);
    }

    // 登录
    public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return response()->json([
            'access_token' => 'bearer '.$token,
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }

    // 查询账号信息
    public function me()
    {
        return response()->json(auth()->user());
    }

}

模仿affiliate代码新建实现admin账号系统的代码

第一步:修改App\Models\Admin model文件

<?php

namespace App\Models;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable implements JWTSubject
{
    use Notifiable;

     /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password'
    ];

    // Rest omitted for brevity

    /**
     * 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 [];
    }
}

第二步:修改routes\local\backend.php

<?php
// 后台用户路由

use Illuminate\Support\Facades\Redis;

Route::namespace('Backend')->group(function(){
    Route::group(['prefix' => 'admin'], function () {
        // 用户登录
        Route::post('login', 'AdminController@login');
        // 用户注册
        Route::post('register', 'AdminController@register');
    });
    
});

Route::group(['namespace' => 'Backend', 'middleware' => 'auth:backend'], function(){
    Route::group(['prefix' => 'admin'], function () {
        // 验证token
        Route::post('me', 'AdminController@me');
    });
});

第三步:修改App\Http\Controllers\Backend\AdminController。方法Auth()就是Auth('frontend')的意思,默认是frontend账号;后台用户使用Auth('backend'),前面配置过了。

<?php

namespace App\Http\Controllers\Backend;
use App\Http\Controllers\Controller;

use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AdminController extends Controller
{
    public function register()
    {

        $email = request()->input('email');
        $password = Hash::make(request()->input('password'));
        $ret = Admin::where('email', $email)->first();
        if($ret) return response()->json(['error' => 'email exist'], 500);

        Admin::create(['email' => $email, 'password'=>$password]);
        return response()->json(['success' => 'registered successfully'], 200);
    }

    public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth('backend')->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return response()->json([
            'access_token' => 'bearer '.$token,
            'expires_in' => auth('backend')->factory()->getTTL() * 60
        ]);
    }

    public function me()
    {
        $user = auth('backend')->user();
        return response()->json($user);
    }
}

效果演示

 

源代码地址:https://github.com/windawake/laravel-repository-pratice/tree/master

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值