Laravel8+SanctumでAPI認証その2(ユーザ登録・ログイン・ログアウト)
1, apiでログインしてみる
https://codelikes.com/use-laravel-sanctum/
https://noumenon-th.net/programming/2020/05/26/sanctum/
routes/api.php
1 2 3 4 5 6 7 8 9 10 |
// laravel8からroutes/web.phpやapi.phpにも、useが必要! use App\Http\Controllers\RegisterController; use App\Http\Controllers\LoginController; // ユーザー登録 Route::post('/register', [RegisterController::class, 'register']); // ログイン Route::post('/login', [LoginController::class, 'login']); // ログアウト Route::post('/logout', [LoginController::class, 'logout']); |
2. コントローラー作成
1 2 |
php artisan make:controller RegisterController php artisan make:controller LoginController |
ユーザー登録コントローラー
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Http\Requests\UserCreateRequest; use App\Providers\RouteServiceProvider; use App\Models\User; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use \Symfony\Component\HttpFoundation\Response; class RegisterController extends Controller { public function register(Request $request) { /** @var Illuminate\Validation\Validator $validator */ $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', 'password' => 'required' ]); if ($validator->fails()) { return response()->json($validator->messages(), Response::HTTP_UNPROCESSABLE_ENTITY); } $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); $json = [ 'data' => $user, 'message' => 'User registration completed', 'error' => '' ]; return response()->json( $json, Response::HTTP_OK); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
php artisan route:list +--------+----------+---------------------+------+------------------------------------------------------------+------------------------------------------+ | Domain | Method | URI | Name | Action | Middleware | +--------+----------+---------------------+------+------------------------------------------------------------+------------------------------------------+ | | GET|HEAD | / | | Closure | web | | | GET|HEAD | api/hello | | Closure | api | | | POST | api/login | | App\Http\Controllers\LoginController@login | api | | | POST | api/logout | | App\Http\Controllers\LoginController@logout | api | | | POST | api/register | | App\Http\Controllers\RegisterController@register | api | | | GET|HEAD | api/user | | Closure | api | | | | | | | App\Http\Middleware\Authenticate:sanctum | | | GET|HEAD | sanctum/csrf-cookie | | Laravel\Sanctum\Http\Controllers\CsrfCookieController@show | web | +--------+----------+---------------------+------+------------------------------------------------------------+------------------------------------------+ |
3. API経由でユーザー登録
1 2 |
curl -X POST -H "Accept: application/json" http://localhost/laravel8/public/api/register -d "name=test" -d "email=test@example.com" -d "password=password" -d "password_confirmation=password" {"data":{"name":"test","email":"test@example.com","updated_at":"2021-09-24T07:38:52.000000Z","created_at":"2021-09-24T07:38:52.000000Z","id":2},"message":"User registration completed","error":""} |
4. LoginController.phpに、ログイン成功後、トークンを返す処理を記述
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; use Illuminate\Validation\ValidationException; use App\Models\User; use \Symfony\Component\HttpFoundation\Response; class LoginController extends Controller { public function login(Request $request) { $credentials = $request->validate([ 'email' => 'required|email', 'password' => 'required' ]); if (Auth::attempt($credentials)) { $user = User::whereEmail($request->email)->first(); $user->tokens()->delete(); $token = $user->createToken("login:user{$user->id}")->plainTextToken; return response()->json(['token' => $token ], Response::HTTP_OK); } return response()->json('Can Not Login.', Response::HTTP_INTERNAL_SERVER_ERROR); } // ログアウトにトークンは不要? public function logout (Request $request) { auth('sanctum')->user()->tokens()->delete(); return response(['message' => 'You have been successfully logged out.'], 200); } } |
5. API経由でログイン
1 2 |
curl -X POST -H "Accept: application/json" http://localhost/laravel8/public/api/login -d "email=test@example.com" -d "password=password" {"token":"1|djb3uFPBnBSahHw6L5D0S4mohtCf8cPWLe09ab2K"} |
6. トークンを使って、認証が必要なAPIを使ってみる
1 2 |
curl -X GET -H "Accept: application/json" -H "Authorization: Bearer djb3uFPBnBSahHw6L5D0S4mohtCf8cPWLe09ab2K" http://localhost/laravel8/public/api/user {"id":2,"name":"test","email":"test@example.com","email_verified_at":null,"created_at":"2021-09-24T07:38:52.000000Z","updated_at":"2021-09-24T07:38:52.000000Z"} |
# 適当なトークンだと弾かれる
1 2 |
curl -X GET -H "Accept: application/json" -H "Authorization: Bearer aaaaa" http://localhost/laravel8/public/api/user {"message":"Unauthenticated."} |
7. API経由でログアウトする(トークンを無効化する)
1 |
curl -X POST -H "Accept: application/json" -H "Authorization: Bearer トークンID" http://localhost/laravel8/public/api/logout |