본문 바로가기
Framework/Laravel Framework

[Laravel] JWT API Server 구축하기(2)

by 원동호 2021. 5. 25.
반응형

구성 : Laravel Framework 8.42.1

 

2021.05.21 - [Framework/Laravel Framework] - [Laravel] JWT API Server 구축하기(1)

 

이번 포스팅에서는 User 모델 이외에 Admin 모델을 만들어 multiple jwt 인증을 진행해보겠다.

 

Admin Model 추가

User Model과 내용은 동일하다. migration도 users table과 동일하게 구성했다.

php artisan make:model Admin
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;


class Admin extends Authenticatable implements JWTSubject {
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

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

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

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

 

Auth Guard 수정

config\auth.php

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

        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
        //admin API로 사용할 guard를 추가해준다.
        'admin-api' => [ 
            'driver' => 'jwt',
            'provider' => 'admins',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
        //추가
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],
    ],
 ...

 

미들웨어 그룹 추가

app\Http\Kernel.php

protected $middlewareGroups = [
      	...
        // users use 
        'api' => [
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
        
        //admins use
        'admin-api' => [
            // 'throttle:admin-api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

 

컨트롤러 작성하기

routes\api.php

prefix로 users, admins api를 구분해준다.

Route::group([
    'middleware' => 'api',
    'prefix' => 'users'
], function () {
    Route::post('login', [UserController::class, 'login']);
    Route::post('logout', [UserController::class, 'logout']);
    Route::post('refresh', [UserController::class, 'refresh']);
    Route::post('me', [UserController::class, 'me']);
    Route::post('register', [UserController::class, 'register']);
});

Route::group([
	//app\Http\Kernel.php의 middlewareGroups에 작성한 값을 넣어준다.
    'middleware' => 'admin-api',
    'prefix' => 'admins'
], function () {
    Route::post('login', [AdminController::class, 'login']);
    Route::post('logout', [AdminController::class, 'logout']);
    Route::post('refresh', [AdminController::class, 'refresh']);
    Route::post('me', [AdminController::class, 'me']);
    Route::post('register', [AdminController::class, 'register']);
});

 

아래는 현재까지 등록된 route list이다. 테스트는 전 포스팅에서 진행했으므로 생략한다!

+--------+----------+---------------------+------+-----------------------------------------------+------------+
| Domain | Method   | URI                 | Name | Action                                        | Middleware |
+--------+----------+---------------------+------+-----------------------------------------------+------------+
|        | GET|HEAD | /                   |      | Closure                                       | web        |
|        | POST     | api/admins/login    |      | App\Http\Controllers\AdminController@login    | api        |
|        |          |                     |      |                                               | admin-api  |
|        | POST     | api/admins/logout   |      | App\Http\Controllers\AdminController@logout   | api        |
|        |          |                     |      |                                               | admin-api  |
|        |          |                     |      |                                               | jwt.verify |
|        | POST     | api/admins/me       |      | App\Http\Controllers\AdminController@me       | api        |
|        |          |                     |      |                                               | admin-api  |
|        |          |                     |      |                                               | jwt.verify |
|        | POST     | api/admins/refresh  |      | App\Http\Controllers\AdminController@refresh  | api        |
|        |          |                     |      |                                               | admin-api  |
|        |          |                     |      |                                               | jwt.verify |
|        | POST     | api/admins/register |      | App\Http\Controllers\AdminController@register | api        |
|        |          |                     |      |                                               | admin-api  |
|        | POST     | api/users/login     |      | App\Http\Controllers\UserController@login     | api        |
|        | POST     | api/users/logout    |      | App\Http\Controllers\UserController@logout    | api        |
|        |          |                     |      |                                               | jwt.verify |
|        | POST     | api/users/me        |      | App\Http\Controllers\UserController@me        | api        |
|        |          |                     |      |                                               | jwt.verify |
|        | POST     | api/users/refresh   |      | App\Http\Controllers\UserController@refresh   | api        |
|        |          |                     |      |                                               | jwt.verify |
|        | POST     | api/users/register  |      | App\Http\Controllers\UserController@register  | api        |
+--------+----------+---------------------+------+-----------------------------------------------+------------+

 

도움이 되셨다면 하트 및 댓글 부탁드립니다♥

반응형

댓글