This is the 28th day of my participation in the August Text Challenge.More challenges in August

Set up JWT certification system

JWT is a typical application developed separately at the front and back ends. It will be authenticated by JSON-Web-Tokens (JWT). JWT is a lightweight authentication specification that features authentication and data exchange. Just like going out to travel to check in the hotel, you can enter the room only after the authentication of the room card, and the room card must be authorized to obtain in advance.

Install using Composer

Execute the composer command:

composer require tymon/jwt-auth 1.*@rc
Copy the code

It may take a little longer here, so please be patient and go for another cup of coffee.

Enabling Middleware Authentication

Open bootstrap/app.php and uncomment the following four: Open Facade.

$app->withFacades();
Copy the code

Open the Eloquent.

$app->withEloquent();
Copy the code

Enable the middleware.

$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);
Copy the code

Register middleware.

$app->register(App\Providers\AuthServiceProvider::class);
Copy the code

Then append the service provider to the line that registers the middleware.

$app->register(\Tymon\JWTAuth\Providers\LumenServiceProvider::class);
Copy the code

Generate encryption key

Open terminal execution:

php artisan jwt:secret
Copy the code

Env will add a new line of JWT key to the.env file. Note that this cannot be modified arbitrarily.

Update model

Open appuser.php and update the User model to the following:

  • Add JWTSubject and inherit.
  • Add getJWTIdentifier and getJWTCustomClaims.

      

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Model implements AuthenticatableContract.AuthorizableContract.JWTSubject
{
    use Authenticatable.Authorizable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name'.'email',];/**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password',];/**
     * 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[]; }}Copy the code

Registration of the Facade

$app->withFacades();

$app->withFacades(true['Tymon\JWTAuth\Facades\JWTAuth'= >'JWTAuth'.'Tymon\JWTAuth\Facades\JWTFactory'= >'JWTFactory',]);Copy the code

Set the auth. PHP

Create a new config folder in the project root directory and create auth.php. Write the following: this is a direct copy of \vendor\laravel\lumen-framework\config\auth.php and modify it.


      

return [

    'defaults'= > ['guard' => env('AUTH_GUARD'.'api')],'guards'= > ['api'= > ['driver'= >'jwt'.'provider'= >'users',]],'providers'= > ['users'= > ['driver'= >'eloquent'.'model' => \App\User::class,
        ],
    ],

    'passwords'= > [//]];Copy the code

Resolve cross-domain problems

Create a new corshttp.php file under appHttpMiddleware and say:


      

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class CorsHttp
{
    private $headers;
    private $allow_origin;

    public function handle(Request $request, \Closure $next)
    {
        $this->headers = [
            'Access-Control-Allow-Methods'= >'GET, POST, PUT, DELETE'.'Access-Control-Allow-Headers'= >$request->header('Access-Control-Request-Headers'),
            'Access-Control-Allow-Credentials'= >'true'.// Allow clients to send cookies
            'Access-Control-Max-Age'= >1728000 // This field is optional and specifies the validity period of this precheck request, during which no other precheck request is issued.
        ];

        $this->allow_origin = [
            // 'http://localhost',
            / / 'http://192.168.1.17:8080'
        ];
        $origin = isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN'] : ' ';

        If origin is not in the allowed list, return 403
        // if (! in_array($origin, $this->allow_origin) && ! empty($origin))
        // return new Response('Forbidden', 403);
        If it is a complex request, return 200 and allow origin
        if ($request->isMethod('options'))
            return $this->setCorsHeaders(new Response('OK'.200), $origin);
        // If it is a simple request or a non-cross-domain request, set the header as usual
        $response = $next($request);
        $methodVariable = array($response.'header');
        // This is because after the session global middleware is enabled, the frequent header method does not exist, so this judgment is added to the header method exists only when the header method is set
        if (is_callable($methodVariable.false.$callable_name)) {
            return $this->setCorsHeaders($response.$origin);
        }
        return $response;
    }

    / * * *@param $response
     * @return mixed
     */
    public function setCorsHeaders($response.$origin)
    {
        foreach ($this->headers as $key= >$value) {
            $response->header($key.$value);
        }
        // if (in_array($origin, $this->allow_origin)) {
        $response->header('Access-Control-Allow-Origin'.$origin);
        $request-request ($request-request, $authorization-type); $request-request ($request-request, $authorization-type);
        // } else {
        // $response->header('Access-Control-Allow-Origin', '');
        // }
        return $response; }}Copy the code

In bootstrapapp.php, add:

$app->middleware([
    \App\Http\Middleware\CorsHttp::class,
]);
Copy the code

Develop API interface specifications

Request mode specification

We standardize the interface to obtain data in GET mode, modify/add/delete operations in POST mode.

GET (SELECT) : Retrieves one or more resources from the server. POST (CREATE) : Modifies, adds, or deletes a resource on the server.Copy the code

Interface path specification

We define an interface address according to domain name + module name + method name. For example, in our project, we need to query user information (getUserInfo) from user module, then the interface address is:

/user/getUserInfo
Copy the code

Returns the data structure specification

{
  code: 0.// 0: The operation/data acquisition succeeds. Other: the operation fails
  data: {} | |null.msg: ' '
}
Copy the code

Status code specification

If the HTTP status code returns 200, then the business data can be returned according to the above structure. Secondly, we specify the following common status codes and processing methods:

400: Bad Request 500: Internal Server Error 401: Unauthorized Login Is returned 403: Forbidden 404: Not FoundCopy the code

Encapsulate some utility classes

Create a Lib directory in the app directory for the libraries we will encapsulate later and create a new util.php file. We’ll start by wrapping two methods as required, one for random ID generation (createId) and one for front-end Ajax data return (ajaxMsg).

<? php namespace App\Lib;/** * Util class */
class Util
{
    @param int $len * @return string */
    public static function createId($len = 11)
    {
        if ($len < 6 || $len > 11) {
            return false;
        }
        //ID first digit is not0
        $first = mt_rand(1.9);
        $other = ' ';
        for ($i = 0; $i < $len - 1; $i++) {
            $other .= mt_rand(0.9);
        }
        return $first . $other;
    }

    /** * ajaxMsg function Response * @param [string] $code Return code * @param [string] $MSG Return message * @param [string] $data Returns data packets * @param [int] $status_code Returns status code * @return JSON */
    public static function ajaxMsg($code = ' ', $msg = ' ', $data = ' ', $status_code = 200)
    {
        return response()
            ->json([
                'code' => $code, //Return status code'data' => $data, //Return the data'msg' => $msg, //Return hint], $status_code)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }
    
  	/** * isPsw function * Password verification * The password must contain uppercase and lowercase letters and digits. Special characters cannot be used. The value contains 6 to 10 characters * @param [type] $data * @return bool */
    public static function isPsw($data)
    {
        $reg = '/ ^ (? =.*\d)(? =.*[a-z])(? =. * [a-z]). 6, 20} {$/ ';
        return preg_match($reg, $data) ? true : false; }}Copy the code

Welcome to other articles

  • Internationalize your website with Vite2+Vue3 | August Update Challenge
  • Actual combat: The front-end interface request parameters are confused
  • Practice: Implement a Message component with Vue3
  • Actual combat: Vue3 Image components, incidentally support lazy loading
  • What updates does One Piece, vue.js 3.0 bring
  • An article digests the major new features of ES7, ES8, and ES9
  • Common problems and solutions for technical teams
  • Introduction to 10 common new features in ES6
  • Vue3 script Setup syntax is really cool