Laravel + react actually builds enterprise-level highly concurrent distributed e-commerce applets (1)
Use laravel7 + react as a whole to create the entire e-commerce applet. It will involve knowledge of high concurrency, mysql's sub-database and sub-table, master-slave read-write separate configuration, use of redis cluster, use of cache system, use of queue system, etc.
First initialize a laravel project. Then configure the .env
file.
Infrastructure
When we use front-end separation, we must consider cross-domain issues and security issues. Cross-domain use cors
solution, cors
the solution built into laravel7 , we just need to modify the config/cors.php
configuration file.
Change the value inside. The reason for changing this value is because we will use jwt to pass a token request header to verify. At this time, a cross-domain error is still reported, so change the supports_credentials
value to true. If you do not report an error, you do not need to modify it.
'supports_credentials' => true,
Change the value of this parameter to true.
jwt
The solution to the security problem is the installed jwt
package.
composer require lcobucci/jwt
Add the following route to the routes / api.php routing file
//获取jwt token
Route::post('/require_token', 'JWT\RequireTokenController@requireToken');
Create a new jwt.php
file under config with the following content
<?php
return [
'JWT_SECRET' => env('JWT_SECRET','DvYUz+woS7vVJe6ldY+PqWoUbhIyY9rShzM0NAfzxdU='),
'JWT_EXP_TIME' => env('JWT_EXP_TIME','36000'),
];
In the .env
following into the
# jwt
JWT_SECRET=DvYUz+woS7vVJe6ldY+PqWoUbhIyY9rShzM0NAfzxdU=
JWT_EXP_TIME=36000 //过期时间
In the app/http/middleware
creation middleware jwtCheck.php
, which reads as follows
<?php
namespace App\Http\Middleware;
use App\Models\Sys\ErrorModel;
use Closure;
use \Lcobucci\JWT\Parser;
use \Lcobucci\JWT\Signer\Hmac\Sha256;
class jwtCheck
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$parser = new Parser;
$signer = new Sha256;
$secret = config('jwt.JWT_SECRET');
if($request->hasHeader('Authorization')){
$token = $request->header('Authorization');
//解析token
$parse = $parser->parse($token);
//验证token合法性
if (!$parse->verify($signer, $secret)) {
return response()->json(['code'=>ErrorModel::JWT_ERROR, 'msg'=>'令牌错误!']);
}
//验证是否已经过期
if ($parse->isExpired()) {
return response()->json(['code'=>ErrorModel::JWT_ERROR, 'msg'=>'令牌过期!']);
}
}else{
return response()->json(['code'=>ErrorModel::JWT_ERROR, 'msg'=>'令牌缺失!']);
}
//把token放到参数里面
request()->offsetSet('token', $token);
return $next($request);
}
}
Add the following content to the variables in the app/http
following Kernel.php
file $routeMiddleware
to register the middleware to the system.
'jwtCheck' => \App\Http\Middleware\jwtCheck::class,
Controller
Create a controller
In app/http/controller
the following create a jwt
folder, then jwt
create a folder inside RequireTokenController.php
the file.
<?php
namespace App\Http\Controllers\JWT;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use \Lcobucci\JWT\Builder;
use \Lcobucci\JWT\Signer\Hmac\Sha256;
use Illuminate\Support\Facades\Redis;
class RequireTokenController extends Controller
{
public function requireToken(Builder $builder, Sha256 $signer) {
$secret = config('jwt.JWT_SECRET');
$time = time();
$expTime = config('jwt.JWT_EXP_TIME');
do {
//设置header和payload,以下的字段都可以自定义
$builder->setIssuer("cmp.wliot.com") //发布者
->setAudience("cmp.wliot.com") //接收者
->setId("abc", true) //对当前token设置的标识
->setIssuedAt($time) //token创建时间
->setExpiration($time + $expTime) //过期时间
// ->setNotBefore($time + 5) //当前时间在这个时间前,token不能使用
->set('uid', 30061); //自定义数据
//设置签名
$builder->sign($signer, $secret);
//获取加密后的token,转为字符串
$token = (string)$builder->getToken();
} while (Redis::exists($token));
//存入redis
// Redis::setex($token, $expTime, json_encode([]));
return $this->success($token);
}
}
In this $this->success()
method is used, this method comes from the controller class, we need to write this method.
In app/http
the following create a Utils
folder created inside Success.php
the file.
<?php
namespace App\Http\Utils;
use App\Models\Sys\ErrorModel;
trait Success {
function success($data = []) {
$res = ['code'=>'0','msg'=>'请求成功!', 'data'=>$data];
return response()->json($res);
}
}
Modify app/http/controllers/controller.php
file
use App\Http\Utils\Success; //引入刚才的文件
class Controller extends BaseController {
use AuthorizesRequests, DispatchesJobs, ValidatesRequests, Success; //在这里添加Success 也就是刚才的文件。
}
Redis is used in this, so we need to start your local redis server. After starting, you can access the route we filled in above, and use postman to access your route.
You can see that the correct token was returned.
We need to use this token in subsequent access requests. We add it to the request header. Create a new Authorization
key in the request header , his value is our token.