-
composer.json
Open in GitHub{ // "require": { "php": "^7.3|^8.0", // "laravel/sanctum": "^2.8" }, // }
-
app/Models/User.php
Open in GitHubuse Laravel\Sanctum\HasApiTokens; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasApiTokens; // }
-
app/Http/Controllers/Api/Auth/LoginController.php
Open in GitHubuse Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Route; class LoginController extends Controller { public function login(Request $request) { $input = $this->validate($request, [ 'email' => 'required|email|exists:users,email', 'password' => 'required|min:6', ], [ 'email.exists' => 'The user credentials were incorrect.', ]); request()->request->add([ 'grant_type' => 'password', 'client_id' => env('PASSWORD_CLIENT_ID'), 'client_secret' => env('PASSWORD_CLIENT_SECRET'), 'username' => $input['email'], 'password' => $input['password'], ]); $response = Route::dispatch(Request::create('/oauth/token', 'POST')); $data = json_decode($response->getContent(), true); if (!$response->isOk()) { return response()->json($data, 401); } return $data; } public function logout(Request $request) { $accessToken = $request->user()->token(); DB::table('oauth_refresh_tokens') ->where('access_token_id', $accessToken->id) ->update([ 'revoked' => true, ]); $accessToken->revoke(); return response()->json([], 201); } }
-
routes/api/auth.php
Open in GitHubuse Illuminate\Http\Request; use Illuminate\Support\Facades\Route; Route::group(['middleware' => 'auth:sanctum'], function() { Route::get('/me', function (Request $request) { return $request->user(); }); });