JSON Web令牌(JWT)是JSON对象,用于通过Web(两个方之间)安全地传输信息。它可用于身份验证系统,也可用于信息交换。
令牌主要由标头,有效载荷,签名组成。这三个部分被点分开(。)。 JWT定义了我们从一方发送到另一方的信息结构,并以两种形式序列化,供应。
使用每个请求和响应,序列化方法主要用于通过网络传输数据。虽然供应方法用于将数据读取到网络令牌。
在本教程中,我想向您展示如何用Lumen 8。
构建JWT身份验证的API让我们代码!
安装管腔
第一步,您必须安装新的Lumen项目。如果要使用最新版本的Lumen,则可以在下面运行命令:
composer create-project --prefer-dist laravel/lumen blog
但是,如果您想使用特定版本的管腔,则可以在下面运行命令
composer create-project laravel/lumen blog "5.*.*"
您只需要更改主版本号(5、6、7、8等)
进行数据库迁移
- 确保您的env文件连接到某些数据库地址
DB_CONNECTION=mysql
DB_HOST=type-your-host-here
DB_PORT=3306
DB_DATABASE=type-your-db-here
DB_USERNAME=type-your-username
DB_PASSWORD=type-your-password
- 创建一个新的迁移文件,运行此命令
php artisan make:migration create_users_table
- 打开迁移文件,并在下面添加代码
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
- 运行迁移
php artisan migrate
此命令,将执行迁移文件并在数据库中创建新表。
安装JWT软件包
通过作曲家安装jwt-auth
composer require tymon/jwt-auth:*
生成JWT秘密密钥
生成密钥秘密JWT,在下面运行命令
php artisan jwt:secret
设置文件夹和重要配置文件
- 创建新文件夹,命名为 config (与 app 文件夹相同的级别)
-
您必须从 vendor/tymon/jwt-auth/config/config.php config 文件夹复制文件,然后将文件命名为 jwt.php
-
接下来,在 config 文件夹中创建新文件, auth.php
- 打开文件 app.php (bootstrap/app.php),编辑并添加此代码
// Uncomment this line
$app->withFacades();
$app->withEloquent();
// Add this line
$app->configure('jwt');
$app->configure('auth');
//Then uncomment the auth middleware
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
$app->register(App\Providers\AuthServiceProvider::class);
// Add this line in the same file:
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
- Open auth.php (config/auth.php)添加此代码
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Models\User::class
]
]
];
创建模型
让我们制作新文件模型,user.php(app/models/user.php),添加代码下面:
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
//this is new
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable;
/**
* 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 [];
}
}
创建控制器
接下来,您必须制作新的控制器文件, authcontroller (app/http/http/controllers/authcontroller),添加thic代码:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'refresh', 'logout']]);
}
/**
* Get a JWT via given credentials.
*
* @param Request $request
* @return Response
*/
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|string',
'password' => 'required|string',
]);
$credentials = $request->only(['email', 'password']);
if (! $token = Auth::attempt($credentials)) {
return response()->json(['message' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'user' => auth()->user(),
'expires_in' => auth()->factory()->getTTL() * 60 * 24
]);
}
}
设置路线
open web.php file(路由/web.php),添加此代码
<?php
/** @var \Laravel\Lumen\Routing\Router $router */
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$router->get('/', function () use ($router) {
return $router->app->version();
});
$router->get('/get-key', function() {
return \Illuminate\Support\Str::random(32);
});
Route::group([
'prefix' => 'api'
], function ($router) {
Route::post('login', 'AuthController@login');
Route::post('logout', 'AuthController@logout');
Route::post('refresh', 'AuthController@refresh');
Route::post('user-profile', 'AuthController@me');
});
添加加密密钥应用程序
您不能运行 php工匠钥匙:在管腔中生成(如在laravel中),因此您必须通过呼叫路线/get-key手动生成
打开浏览器,请访问此链接 http://localhost:8000/get-key ,在Env File
中复制并将键粘贴到app_key刷新设置
更改Env文件后,您必须运行
php artisan cache:clear
跑步管道
使用此命令运行管腔
php -S localhost:8000 -t public
打开邮递员测试您的API端点的