-
라라벨[Laravel] JWT 구현PHP/라라벨[Laravel] 2020. 9. 5. 23:34
1. jwt 설치
- composer require tymon/jwt-auth
2. config에 jwt 파일추가
- php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
- config/jwt.php 파일 확인
3. .env 파일에 secret키추가
- php artisan jwt:secret
- .env 파일에 JWT_SECRET 키 확인
4. app/Http/Kernel.php
$routeMiddleware 변수안에 아래내용 추가 - protected $routeMiddleware =[ 'auth.jwt' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class, // JWT middleware ]
5. routes/api.php
샘플용 routes 적용 ---------------------------- Route::post('login', 'ApiController@login'); Route::post('register', 'ApiController@register'); Route::group(['middleware' => 'auth.jwt'], function () { Route::get('logout', 'ApiController@logout'); Route::get('tasks', 'TaskController@index'); Route::get('tasks/{id}', 'TaskController@show'); Route::post('tasks', 'TaskController@store'); Route::put('tasks/{id}', 'TaskController@update'); Route::delete('tasks/{id}', 'TaskController@destroy'); });
6. app/User.php
namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Tymon\JWTAuth\Contracts\JWTSubject; class User extends Authenticatable implements JWTSubject { use 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', ]; /** * 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 []; } }
7. 회원가입 룰적용
- php artisan make:request RegistrationFormRequest
8. app/Http/Requests/RegistrationFormRequest.php
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class RegistrationFormRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required|string', 'email' => 'required|email|unique:users', 'password' => 'required|string|min:6|max:10' ]; } }
9. api 컨트롤러 생성
- php artisan make:controller APIController
10. Controllers/APIController.php
<?php namespace App\Http\Controllers; use JWTAuth; use App\User; use Illuminate\Http\Request; use Tymon\JWTAuth\Exceptions\JWTException; use App\Http\Requests\RegistrationFormRequest; class APIController extends Controller { /** * @var bool */ public $loginAfterSignUp = true; /** * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function login(Request $request) { // $input = $request->only('email', 'password'); $input = $request->only('user_id', 'password'); $token = null; if (!$token = JWTAuth::attempt($input)) { return response()->json([ 'success' => false, 'message' => 'Invalid Email or Password', ], 401); } return response()->json([ 'success' => true, 'token' => $token, ]); } /** * @param Request $request * @return \Illuminate\Http\JsonResponse * @throws \Illuminate\Validation\ValidationException */ public function logout(Request $request) { $this->validate($request, [ 'token' => 'required' ]); try { JWTAuth::invalidate($request->token); return response()->json([ 'success' => true, 'message' => 'User logged out successfully' ]); } catch (JWTException $exception) { return response()->json([ 'success' => false, 'message' => 'Sorry, the user cannot be logged out' ], 500); } } /** * @param RegistrationFormRequest $request * @return \Illuminate\Http\JsonResponse */ public function register(RegistrationFormRequest $request) { $user = new User(); $user->name = $request->name; $user->email = $request->email; $user->password = bcrypt($request->password); $user->save(); if ($this->loginAfterSignUp) { return $this->login($request); } return response()->json([ 'success' => true, 'data' => $user ], 200); } }
'PHP > 라라벨[Laravel]' 카테고리의 다른 글
라라벨 5.3 설치방법 (XAMPP) (0) 2017.07.31 Laravel[라라벨] PHP 프레임 워크란!! (0) 2017.01.19