Laravel uses JWT to implement API user authorization

Part I installation of JWT

Step 1. Use Composer to install tymon / JWT auth:
`composer require tymon/jwt-auth 1.0.0-rc.3

Step 2. Add a service provider (laravel 5.4 and below, no need to add 5.5 and above),
Add the following line to the providers array of the config/app.php file:

<?php
// File: app.php
'providers' => [
    // other code
    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]

Step 3. Publish the configuration file,
Run the following command to publish the configuration file of JWT auth:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Step 4. Generate the key,
This command adds a new line JWT_SECRET=secret to your. env file.
php artisan jwt:secret

Part 2 start configuration

Step 5. Configure Auth guard`
In the config/auth.php file, you need to update the guards/driver to jwt,
It can only be used with Laravel 5.2 and above.

<?php
    'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],
// other code
'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

Step 6. Change the User Model,
Implement the TymonJWTAuthContractsJWTSubject interface on the User Model,
Two methods, getJWTIdentifier() and getJWTCustomClaims(), are implemented.

<?php
namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    // other code

    // 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 [];
    }
}

The third part quickly create DEMO test

Step 7. Add some basic authentication routes:

<?php
Route::group([
    'middleware' => 'api',
    'prefix' => 'auth'
], function ($router) {
    Route::post('login', 'AuthController@login');
    Route::post('register', 'AuthController@register');
    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::post('me', 'AuthController@me');
});

Step 8. Create AuthController = > PHP artican make: controller AuthController:

<?php
namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

    /**
     * The user obtains the JWT Token with the mailbox password
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

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

    /**
     * Register new users
     */
    public function register(Request $request)
    {
        // data verification
        // data validation
        $validator = Validator::make($request->all(), [
            'name'       => 'required',
            'email'      => 'required|email',
            'password'   => 'required',
            'c_password' => 'required|same:password'
        ]);

        if ($validator->fails()) {
            return response()->json(['error'=>$validator->errors()], 401);
        }

        // Read parameters and save data
        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);

        // Create Token and return
        return $user;
    }

    /**
     * Get authenticated users
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Refresh Token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }


    /**
     * 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()->factory()->getTTL() * 60
        ]);
    }
}

Step 9. Use Postman to test the API:

To test API data acquisition, you need to add Token; format in headers
key=Authorization, value=Bearer space token

Token refresh:

Tags: PHP JSON Laravel REST

Posted on Mon, 02 Dec 2019 13:30:01 -0500 by solar_ninja