This is the 18th day of my participation in the August Genwen Challenge.More challenges in August

Dingo/Api certification document

JWT Introduction documentation

Tymon/JWT-AUth API authentication

1.1 installation tymon/JWT – auth

Tymon/JwT-Auth installation documentation

Install Tymon/jwT-auth

composer require tymon/jwt-auth

1-1 Installation error can be seen, no error can be crossed.

If an error occurs during the installation process, it is recommended to use PHP7.x first because the higher version is not suitable for the current version. If you have a higher version of PHP in Homestead, you can lower the version:

Sudo update-alternatives –config PHP when executed, all current PHP versions and numbers will be listed. Enter the number and switch to the current version.

Remember after the current switchhomesteadThe PHP environment should also correspond tophpVersion, modifyHomestead.yamlRemember when you’re donesudo vagrant reload --provisionRestart the VM.

Publish the configuration file and generate JWT_SECRET

1. Publish the configuration file

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Generate JWT_SECRETphp artisan jwt:secret

Update the User model

Authentication is generally user-based, so we modify the user model:Add two more methods:

/**
     * 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

4. Configure the Auth Guard

Dingo/API configuration

In the config/api.php file:

'auth'= > ['jwt'= >'Dingo\Api\Auth\Provider\JWT',].Copy the code

3. Certification examples

3.1 Failure Example

1. Authenticate routes

Add a route to log in under Routes/API:

    // The route to log in
    $api->group(['middleware'= >'api.auth'].function($api) {
        $api->get('users', [\App\Http\Controllers\TestController::class, 'users']);
    });
Copy the code

2. Authentication routing method

    public function users() {
        $users = User::all();
        return $this->response->collection($users.new UserTransformer);
    }
Copy the code

Effect:You can see that authentication is required.

3.2 Successful Examples

1. Login route

    // Perform login
    $api->post('login', [\App\Http\Controllers\TestController::class, 'login']);
Copy the code

2. Login routing method

We use firstdd(bcrypt('12345')Obtain the encrypted ciphertext:To find the data in the database, replace the password:Then log in to the routing method

    public function login(Request $request) {
        // dd(bcrypt('12345'));
        $credentials = request(['email'.'password']);

        if (!$token = auth('api')->attempt($credentials)) {
            return $this->response->errorUnauthorized();
        }

        return $this->respondWithToken($token);
    }

     /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token'= >$token.'token_type'= >'Bearer'.'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }
Copy the code

postmanIn the test: You can see that gives us a successful returntokenThe copytokenRequest,usersTo:You can see that a successful request is returned to the interface that requires authentication.

4. Obtain user information based on token

    public function users() {
        // $users = User::all();
        // return $this->response->collection($users, new UserTransformer);

        // Get user information from token
        $user = app('Dingo\Api\Auth\Auth')->user();
        return $user;
    }
Copy the code

You can also use:

        $user = auth('api')->user();
        return $user;
Copy the code

If you find this article helpful on your way to learning PHP, please follow me to like and comment on it. Thank you, your blog is definitely another support for me to write