Laravel + react combat to create enterprise-level high concurrent distributed e-commerce applet (1)-infrastructure

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 .envfile.

Infrastructure

When we use front-end separation, we must consider cross-domain issues and security issues. Cross-domain use corssolution, corsthe solution built into laravel7 , we just need to modify the config/cors.phpconfiguration 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_credentialsvalue 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.

jwtThe solution to the security problem is the installed jwtpackage.

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.phpfile 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 .envfollowing into the


# jwt
JWT_SECRET=DvYUz+woS7vVJe6ldY+PqWoUbhIyY9rShzM0NAfzxdU=   
JWT_EXP_TIME=36000  //过期时间

In the app/http/middlewarecreation 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/httpfollowing Kernel.phpfile $routeMiddlewareto register the middleware to the system.

'jwtCheck' => \App\Http\Middleware\jwtCheck::class,

Controller

Create a controller

In app/http/controllerthe following create a jwtfolder, then jwtcreate a folder inside RequireTokenController.phpthe 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/httpthe following create a Utilsfolder created inside Success.phpthe 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.phpfile


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.

Insert picture description here

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 Authorizationkey in the request header , his value is our token.

Published 30 original articles · praised 6 · 50,000+ views

Guess you like

Origin blog.csdn.net/Thepatterraining/article/details/105469604