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
中注册服务提供者
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
3、生成配置文件
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
此命令会在 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 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 = [
'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' => App\Models\Admin::class,
]
8、在 AdminController
中添加如下代码:
<?php
namespace App\Http\Controllers\Api\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Admin;
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)