Tymon / JWT auth 1.0.0-beta. 1 practice of larevel using JWT for API authentication

Time:2020-11-1

install

take"tymon/jwt-auth": "1.0.0-beta.1"Add to composer.json Executioncomposer update

Providers

config/app.phpInprovidersAddTymon\JWTAuth\Providers\LaravelServiceProvider::class,

Class Aliases

config/app.phpInaliasesAdd'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class

Modify authentication driver

modifyconfig/auth.php, change the driver of the API to JWT. As follows:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ]

Add route

stayroutes/api.phpAdd the following routes in:

$api = app('Dingo\Api\Routing\Router');

$api->version('v1', ['namespace' => 'App\Http\Controllers\Api\V1'], function($api) {
    $api->post('token', ' [email protected] '; // get token
    $api->post('refresh-token', ' [email protected] '; // refresh token

    $api->group(['middleware' => ['auth:api']], function($api) {
        $api->post('logout', ' [email protected] '; // log out
        $api->get('me', ' [email protected] '; // about me
    });

});

AppUser.php

add togetJWTIdentifierandgetJWTCustomClaimsImplement authenticatable user contract

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject as AuthenticatableUserContract;

class User extends Authenticatable implements AuthenticatableUserContract
{


    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey(); // Eloquent model method
    }

    /**
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

}

Controllers needed to implement routing

<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Api\V1\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Auth;

class UserController extends Controller
{

    protected $guard = 'api';

    /**
     *Get token
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function token(Request $request)
    {
        $credentials=[
            'email' => $request->email,
            'password'  => $request->password,
            'status' => 0,
        ];

        try {
            if (! $token = Auth::guard($this->guard)->attempt($credentials)) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        return response()->json(compact('token'));
    }

    /**
     * @return mixed
     */
    public function refershToken()
    {
        $token = Auth::guard($this->guard)->refresh();

        return $this->response->array(compact('token'));
    }

    /**
     *Personal information
     *
     * @return User|null
     */
    public function me()
    {
        return Auth::guard('api')->user();
    }

    /**
     *Exit
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        Auth::guard($this->guard)->logout();
        return response()->json(['status' => 'ok']);
    }
}

Original address
http://moell.cn/article/37