본문 바로가기
Work

Laravel + JWT 구현 (8.83.27)

by 왕고미 2023. 12. 18.

1. composer require tymon/jwt-auth
: jwt 패키지 설치

2. php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
:jwt-auth.php 구성 파일 개시

3. php artisan jwt:secret
: JWT 시크릿 키 생성

4. Laravel Auth Guard 수정

: config/auth.php 

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

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

5. JWT 미들웨어 생성
php artisan make:middleware JwtMiddleware


<?php

namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Illuminate\Http\Request;

class JwtMiddleware extends BaseMiddleware {

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
        try {
            $user = JWTAuth::parseToken()->authenticate();
        } catch (Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException) {
                return response()->json(['status' => 'Token is Invalid'], 403);
            } else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException) {
                return response()->json(['status' => 'Token is Expired'], 401);
            } else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenBlacklistedException) {
                return response()->json(['status' => 'Token is Blacklisted'], 400);
            } else {
                return response()->json(['status' => 'Authorization Token not found'], 404);
            }
        }
        return $next($request);
    }
}

6. 생성된 미들웨어를 Kernel.php에 등록

protected $routeMiddleware = [
............
        'auth.jwt' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class, // JWT middleware
        'jwt.verify' => \App\Http\Middleware\JwtMiddleware::class,
............
    ];

7. 사용자 모델 수정

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

class User extends Authenticatable implements JWTSubject
{
    // ...

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}


8. routes/api.php 파일에서 JWT를 사용하는 라우트를 설정.
Route::group(['middleware' => 'jwt.auth'], function () {
    // 여기에 보호된 라우트를 추가
});

9. 로그인 컨트롤러
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;

public function login(Request $request)
{
    $credentials = $request->only('email', 'password'); //input 받은 ID,PW

    if (Auth::attempt($credentials)) { //인증 시도 
        $token = JWTAuth::attempt($credentials); //인증이 True면 JWTAuth::attempt($credentials)로 토크 받기
        return response()->json(['token' => $token], 200); //리턴하기
    }

    return response()->json(['error' => 'Unauthorized'], 401);
}

 

짜증나게 별거도 아닌거 가지고 엄청 시간 잡아먹었네 진짜.....ㅠ_ㅠ