Laravel 11 JSON Web Token(JWT) API Authentication教程
cighsen02 2024-10-10 14:33:14 阅读 88
在这篇文章中,我将向您展示如何在 laravel 11 应用程序中使用 JWT 令牌进行 API 身份验证。我们将从头开始学习 API、JWT REST API 和 Laravel JWT 身份验证,并创建一个示例 API。
什么是<code>API?
API(应用程序编程接口)只是两个或多个计算机程序之间的一种通信方式。
API 还用于 Web 和移动应用程序开发;因此,构建 REST API 对于任何 Web 和移动应用程序开发人员都非常重要。
什么是JWT
?
JWT 代表 JSON Web 令牌,它是一个开放标准(RFC 7519),它定义了一种紧凑且自包含的方式,用于将信息作为 JSON 对象在各方之间安全地传输。JWT 通常用于授权、信息交换等。
在此示例中,我们将安装 Laravel 11 应用程序。然后,我们将安装api
。然后我们将使用php-open-source-saver/jwt-auth
包来使用JWT
。之后,我们将创建用于用户身份验证的 register、login、refresh、profile 和 logout API。那么,让我们按照以下步骤逐步完成此示例:
按照以下几个步骤在 laravel 11 应用程序中创建一个 restful API 示例。
第一步: 安装 Laravel 11
如果已经安装可以忽略;如果您尚未创建Laravel
应用程序,则可以继续执行以下命令:
composer create-project laravel/laravel example-app
第二步:启用 API 并更新身份验证
默认情况下,laravel 11 API 路由在 laravel 11 中未启用。我们将使用以下命令启用 API:
php artisan install:api
现在,如果用户未进行身份验证,则exception
将调用,我们将返回json
响应。那么,让我们更新app.php
文件。
bootstrap/app.php
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (AuthenticationException $e, Request $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => $e->getMessage(),
], 401);
}
});
})->create();
安装和设置 JWT Auth 软件包
在此步骤中,我们将安装 php-open-source-saver/jwt-auth composer 包。
composer require php-open-source-saver/jwt-auth
包配置文件:
php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"code>
接下来,生成密钥。这将在 .env 文件上添加 JWT 配置值:
php artisan jwt:secret
现在,我们将更新 Auth Guard 配置文件。
config/auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
...
更新 User 模型
在该模型中,我们首先在用户模型上实现Tymon\JWTAuth\Contracts\JWTSubject
合约,然后实现getJWTIdentifier()
和 getJWTCustomClaims()
方法。
app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
/**
* 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 [];
}
}
创建 API 路由
在此步骤中,我们将创建 API 路由。Laravel 提供了用于编写 Web 服务路由的 api.php 文件。因此,让我们向该文件添加新路由。
routes/api.php
<?php
use Illuminate\Support\Facades\Route;
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('/register', [App\Http\Controllers\Api\AuthController::class, 'register']);
Route::post('/login', [App\Http\Controllers\Api\AuthController::class, 'login']);
Route::post('/logout', [App\Http\Controllers\Api\AuthController::class, 'logout'])->middleware('auth:api');
Route::post('/refresh', [App\Http\Controllers\Api\AuthController::class, 'refresh'])->middleware('auth:api');
Route::post('/profile', [App\Http\Controllers\Api\AuthController::class, 'profile'])->middleware('auth:api');
});
创建 Controller 文件
在下一步中,我们创建了一个名为Controller
和AuthController
的新控制器。我在 Controllers 文件夹中创建了一个名为 “Api” 的新文件夹,因为我们将为 API 提供单独的控制器。所以,让我们创建两个控制器:
app/Http/Controllers/Api/Controller.php
<?php
namespace App\Http\Controllers\Api;
abstract class Controller
{
/**
* success response method.
*
* @return \Illuminate\Http\Response
*/
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
/**
* return error response.
*
* @return \Illuminate\Http\Response
*/
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];
if(!empty($errorMessages)){
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
}
app/Http/Controllers/Api/AuthController.php
<?php
namespace App\Http\Controllers\Api;
use App\Models\User;
use Validator;
use Illuminate\Http\Request;
class AuthController extends Controller
{
/**
* Register a User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if($validator->fails()){
return $this->sendError('Validation Error.', $validator->errors());
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['user'] = $user;
return $this->sendResponse($success, 'User register successfully.');
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
$success = $this->respondWithToken($token);
return $this->sendResponse($success, 'User login successfully.');
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function profile()
{
$success = auth()->user();
return $this->sendResponse($success, 'Refresh token return successfully.');
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return $this->sendResponse([], 'Successfully logged out.');
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
$success = $this->respondWithToken(auth()->refresh());
return $this->sendResponse($success, 'Refresh token return successfully.');
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return [
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
];
}
}
所有必需的步骤都已完成,现在您必须键入以下给定的命令并按 Enter 键以运行 Laravel 应用程序:
php artisan serve
现在,转到您的Postman
并检查以下API
。
请确保在详细信息API
中,我们将使用如下所示的请求头,登陆和注册除外:
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
]
实例效果
以下是运行实例截图。
Register API
: 请求方式:POST
, URL
地址: http://localhost:8000/api/auth/register
<code>Login API: 请求方式:POST
, URL
地址: http://localhost:8000/api/auth/login
<code>Profile API: 请求方式:POST
, URL
地址: http://localhost:8000/api/auth/profile
<code>Refresh Token API: 请求方式:POST
, URL
地址: http://localhost:8000/api/auth/refresh
<code>Logout API: 请求方式:POST
, URL
地址: http://localhost:8000/api/auth/logout
转载请注来源:Laravel 11 JSON Web Token(JWT) API Authentication教程 | 土尔网络
下一篇: (附源码)基于web的停车场管理系统设计与实现-计算机毕设 16856
本文标签
声明
本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。