검색해 나온 포스트들은 5.4버전에 대해서만 나와있어서, 5.5에서는 아무짝에 쓸모가 없었다.
라라벨에서 좃인증을 시작해보자.
설치
jwt-auth
171103 기준으로 dev-develop 버전의 패키지를 설치해야한다.
1
| $ composer require tymon/jwt-auth:1.0.0-rc.1
|
service provider 등록
config/app.php1 2 3 4 5 6 7 8 9 10 11
| <?php
'providers' => [ ... Tymon\JWTAuth\Providers\LaravelServiceProvider::class, ],
'alias' => [ ... 'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class ],
|
설정파일 publish
1
| $ php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" --force
|
secret key 생성
1
| $ php artisan jwt:secret
|
연동
API Route 설정
API 가드와 유저 모델을 설정하다.
config/auth.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <?php return [ 'defaults' => [ 'guard' => 'api', 'passwords' => 'users', ],
'guards' => [ ... 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], ],
'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\Member::class, ], ], ... ];
|
Member Model 설정
app/Models/Member.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <?php ...
use Illuminate\Foundation\Auth\User as Authenticatable; use Tymon\JWTAuth\Contracts\JWTSubject; ...
class Member extends Authenticatable implements JWTSubject { public function getJWTIdentifier() { return $this->getKey(); }
public function getJWTCustomClaims() { return []; } }
|
사용하기
login
app/Http/MemberController.php1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <?php public function login(Request $request) { $credentials = $this->validate($request, [ 'id' => 'required|string', 'password' => 'required|string' ]);
if ($token = $this->guard()->attempt($credentials)) { return $this->respondWithToken($token); }
return response()->json(['message' => 'Unauthorized'], 401); }
protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => $this->guard()->factory()->getTTL() * 60 ]); }
public function guard() { return Auth::guard(); }
|
Authorized Routes
application/json 로 설정해야 오류가 예쁘게 반환된다.
token 태우기
1 2 3 4 5
| Authorization: Bearer yourtokens...
https://gracefullight.github.io/me?token=yourtokens...
|
routes
routes/api.php1 2 3 4
| Route::group(['middleware' => 'auth:api'], function() { Route::get('member/logout', 'MemberController@logout'); Route::get('member/me', 'MemberController@me'); });
|
logout
app/Http/MemberController.php1 2 3 4 5
| <?php public function logout(Request $request) { $this->guard()->logout(); return response(null, 204); }
|
refresh
refresh는 auth:api 미들웨어 없이 처리되어야한다.
app/Http/MemberController.php1 2 3 4
| <?php public function refresh() { return $this->respondWithToken($this->guard()->refresh()); }
|
여담
Expired거나 Unauthoriezed경우 status code로 체크하면 된다.
5.5버전 메뉴얼이 부족하다.