
Why do we need to isolate
When the same laravel project has multiple terminals (mobile terminal, management terminal...) and all need to use jwt for user verification , if there are multiple user tables (usually there are), token isolation needs to be done, otherwise there will be a problem that the token on the mobile side can also request the management side, causing the user to exceed his authority.
The reason why this problem occurs is that laravel's jwt token only stores the value of the primary key of the data table by default, and does not distinguish which table it is. So as long as the ID carried in the token exists in your user table, it will lead to unauthorized verification.
Let’s take a look at the original appearance of laravel’s jwt token:
{
"iss": "http://your-request-url",
"iat": 1558668215,
"exp": 1645068215,
"nbf": 1558668215,
"jti": "XakIDuG7K0jeWGDi",
"sub": 1,
"prv": "92d5e8eb1b38ccd11476896c19b0e44512b2aacd"
}
The sub field that carries data is the sub field, and the other fields are the verification fields of jwt.
We only see that the value of sub is 1, and it does not indicate which table or validator it belongs to. When this token passes your verification middleware, you can use different guards to get the user with the corresponding table ID 1 (please check the laravel documentation to learn about guard).
Solution
To solve the problem of user overreaching, we only need to bring our custom fields on the token to distinguish which table or validator generated it, and then Write your own middleware to verify that our custom fields match our expectations.
Add custom information to token
We know that to use jwt verification, the user model must implement the JWTSubject interface (the code is taken from the jwt document):
<?php namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
// 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 [];
}
}
We can Take a look at the functions of these two implemented methods:
- getJWTIdentifier: Get the identifier that will be stored in the jwt statement. In fact, it requires us to return the primary key field name that identifies the user table. Here is what is returned Is the primary key 'id',
- getJWTCustomClaims: Returns an array containing custom key-value pairs to be added to the jwt declaration. An empty array is returned here without any custom information added.
Next we can add our custom information to the user model that implements the getJWTCustomClaims method.
Administrator model:
/**
* 额外在 JWT 载荷中增加的自定义内容
*
* @return array
*/
public function getJWTCustomClaims()
{
return ['role' => 'admin'];
}
Mobile user model:
/**
* 额外在 JWT 载荷中增加的自定义内容
*
* @return array
*/
public function getJWTCustomClaims()
{
return ['role' => 'user'];
}
A role name is added here as the user ID.
The token generated by the administrator will look like this:
{
"iss": "http://your-request-url",
"iat": 1558668215,
"exp": 1645068215,
"nbf": 1558668215,
"jti": "XakIDuG7K0jeWGDi",
"sub": 1,
"prv": "92d5e8eb1b38ccd11476896c19b0e44512b2aacd",
"role": "admin"
}
The token generated by the mobile user will look like this:
{
"iss": "http://your-request-url",
"iat": 1558668215,
"exp": 1645068215,
"nbf": 1558668215,
"jti": "XakIDuG7K0jeWGDi",
"sub": 1,
"prv": "92d5e8eb1b38ccd11476896c19b0e44512b2aacd",
"role": "user"
}
We can see that there is one more of ourselves here The added role field corresponds to our user model.
Next, we will write a middleware ourselves. After parsing the token, we will determine whether it is the role we want. If it matches, it will pass. If it does not match, it will report 401.
Write jwt role verification middleware
Here is a globally usable middleware (recommended to be used before user verification middleware):
<?php /**
* Created by PhpStorm.
* User: wlalala
* Date: 2019-04-17
* Time: 13:55
*/
namespace App\Http\Middleware;
use Closure;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
class JWTRoleAuth extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* @param $request
* @param Closure $next
* @param null $role
* @return mixed
*/
public function handle($request, Closure $next, $role = null)
{
try {
// 解析token角色
$token_role = $this->auth->parseToken()->getClaim('role');
} catch (JWTException $e) {
/**
* token解析失败,说明请求中没有可用的token。
* 为了可以全局使用(不需要token的请求也可通过),这里让请求继续。
* 因为这个中间件的责职只是校验token里的角色。
*/
return $next($request);
}
// 判断token角色。
if ($token_role != $role) {
throw new UnauthorizedHttpException('jwt-auth', 'User role error');
}
return $next($request);
}
}
Register jwt role verification Verification middleware
Register the middleware in app/Http/Kernel.php:
/** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ // ...省略 ... // 多表jwt验证校验 'jwt.role' => \App\Http\Middleware\JWTRoleAuth::class, ];
Use jwt role verification middleware
Next, add the route that requires user verification Add our middleware to the group:
Route::group([
'middleware' => ['jwt.role:admin', 'jwt.auth'],
], function ($router) {
// 管理员验证路由
// ...
});
Route::group([
'middleware' => ['jwt.role:user', 'jwt.auth'],
], function ($router) {
// 移动端用户验证路由
// ...
});
This completes jwt multi-table user verification isolation.
For more Laravel related technical articles, please visit the Laravel Tutorial column to learn!
The above is the detailed content of Laravel jwt multi-table validation isolation. For more information, please follow other related articles on the PHP Chinese website!
Laravel framework skills sharingApr 18, 2025 pm 01:12 PMIn this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.
The difference between laravel and thinkphpApr 18, 2025 pm 01:09 PMLaravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.
Laravel user login function listApr 18, 2025 pm 01:06 PMBuilding user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.
What versions of laravel are there? How to choose the version of laravel for beginnersApr 18, 2025 pm 01:03 PMIn the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.
How to view the version number of laravel? How to view the version number of laravelApr 18, 2025 pm 01:00 PMThe Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.
The latest method of using php framework laravelApr 18, 2025 pm 12:57 PMLaravel is a popular PHP-based web application framework that is popular among developers for its elegant syntax and powerful features. Its latest version introduces many improvements and new features designed to improve the development experience and application performance. This article will dive into Laravel's latest approach, focusing on how to leverage these updates to build more powerful and efficient web applications.
Laravel framework installation methodApr 18, 2025 pm 12:54 PMArticle summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.
How to learn Laravel How to learn Laravel for freeApr 18, 2025 pm 12:51 PMWant to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools







