Laravel¿ª·¢£ºÔõÑùʹÓÃLaravel PassportʵÏÖAPIÉí·ÝÑéÖ¤£¿
laravelÊÇÒ»¸ö¿ªÔ´µÄphp webÓ¦ÓóÌÐò¿ò¼Ü£¬Ö¼ÔÚ×ÊÖú¿ª·¢ÕßÇáËɹ¹½¨¸ßЧµÄwebÓ¦ÓóÌÐò¡£laravel passportÊÇlaravel¿ò¼ÜµÄÒ»²¿·Ö£¬ËüÊÇÒ»¸öʵÏÖoauth2ÐÒéµÄÉí·ÝÑé֤ЧÀÍÆ÷£¬Îªapi¿ª·¢ÌṩÁËÇ¿Ê¢µÄÖ§³Ö¡£ÔÚ±¾ÎÄÖУ¬ÎÒÃǽ«ÏÈÈÝÔõÑùʹÓÃlaravel passportʵÏÖapiÉí·ÝÑéÖ¤¡£
×°ÖÃLaravel Passport
ʹÓÃLaravel Passport֮ǰ£¬ÎÒÃÇÐèÒªÏÈ×°ÖÃËü¡£¿ÉÒÔͨ¹ýÔËÐÐÒÔÏÂÏÂÁîÀ´×°ÖÃLaravel Passport£º
composer require laravel/passport
µÇ¼ºó¸´ÖÆ
×°ÖÃÍê³Éºó£¬»¹ÐèÒªÔËÐÐphp artisan migrateÏÂÁîÀ´½¨ÉèËùÐèµÄÊý¾Ý±í¡£
ÉèÖÃÈÏÖ¤ÖÐÐļþ
ҪʹÓÃLaravel Passport¾ÙÐÐAPIÉí·ÝÑéÖ¤£¬ÎÒÃÇÐèÒª½«ÆäÓëLaravelµÄÈÏÖ¤ÖÐÐļþÍŽáʹÓ᣿ÉÒÔÔÚapp/Http/Kernel.phpÎļþÖÐΪAPI×éÌí¼ÓÏìÓ¦µÄÈÏÖ¤ÖÐÐļþ£º
protected $middlewareGroups = [ 'api' => [ 'throttle:60,1', IlluminateRoutingMiddlewareSubstituteBindings::class, LaravelPassportHttpMiddlewareCreateFreshApiToken::class, ], ];
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬CreateFreshApiTokenÖÐÐļþ½«ÔÚÿ¸öÇëÇóÖмì²éAPIÁîÅÆ£¬²¢ÔÚÐèҪʱ×Ô¶¯Ë¢Ð¸ÃÁîÅÆ¡£
½¨ÉèAPIÈÏ֤·ÓÉ
½ÓÏÂÀ´£¬ÎÒÃÇÐèҪΪAPI½¨ÉèÏìÓ¦µÄÈÏ֤·ÓÉ¡£¿ÉÒÔÔÚroutes/api.phpÎļþÖÐÌí¼ÓÒÔÏ·ÓÉ£º
Route::post('login', 'APIAuthController@login'); Route::post('register', 'APIAuthController@register'); Route::group(['middleware' => ['auth:api']], function() { Route::get('details', 'APIAuthController@details'); // Ìí¼Ó¸ü¶àÐèÒªµÇ¼²Å»ª»á¼ûµÄAPI·ÓÉ });
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬auth:apiÖÐÐļþ½«È·±£Ö»ÓÐÒѾͨ¹ýÉí·ÝÑéÖ¤µÄÓû§²Å»ª»á¼ûÕâЩ·ÓÉ¡£AuthControllerÊÇÎÒÃÇÉԺ󽫽¨ÉèµÄ¿ØÖÆÆ÷£¬ÆäÖаüÀ¨´¦ÀíÉí·ÝÑéÖ¤ºÍAPI·ÓɵÄÂß¼¡£
½¨ÉèAPIÈÏÖ¤¿ØÖÆÆ÷
ÏÖÔÚ£¬ÎÒÃÇÐèÒª½¨Éè´¦ÀíAPIÉí·ÝÑéÖ¤ºÍ·ÓɵĿØÖÆÆ÷¡£¿ÉÒÔʹÓÃÒÔÏÂÏÂÁÉèAuthController£º
php artisan make:controller API/AuthController
µÇ¼ºó¸´ÖÆ
AuthControllerÖÐÓ¦¸Ã°üÀ¨ÒÔÏÂÒªÁ죺
use IlluminateHttpRequest; use IlluminateSupportFacadesAuth; use IlluminateSupportFacadesValidator; use AppUser; class AuthController extends Controller { /** * Óû§×¢²á * * @param IlluminateHttpRequest $request * @return IlluminateHttpResponse */ public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|string|max:255', 'email' => 'required|string|email|unique:users', 'password' => 'required|string|min:6', ]); if ($validator->fails()){ return response(['errors'=>$validator->errors()->all()], 400); } $request['password'] = bcrypt($request['password']); $user = User::create($request->toArray()); $token = $user->createToken('MyApp')->accessToken; return response(['token' => $token], 200); } /** * Óû§µÇ¼ * * @param IlluminateHttpRequest $request * @return IlluminateHttpResponse */ public function login(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|string|email', 'password' => 'required|string', ]); if ($validator->fails()) { return response(['errors'=>$validator->errors()->all()], 400); } if (!Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) { return response(['message' => 'Invalid login credentials'], 400); } $user = $request->user(); $token = $user->createToken('MyApp')->accessToken; return response(['token' => $token], 200); } /** * »ñÈ¡Óû§ÏêϸÐÅÏ¢ * * @param IlluminateHttpRequest $request * @return IlluminateHttpResponse */ public function details(Request $request) { return response()->json(['user' => $request->user()], 200); } }
µÇ¼ºó¸´ÖÆ
register()ÒªÁìÓÃÓÚÓû§×¢²á£¬login()ÒªÁìÓÃÓÚÓû§µÇ¼£¬details()ÒªÁìÓÃÓÚ»ñÈ¡ÒѵÇÈÎÃü»§µÄÏêϸÐÅÏ¢¡£ÐèҪעÖصÄÊÇ£¬register()ºÍlogin()ÒªÁ콫ΪÒѾͨ¹ýÑéÖ¤µÄÓû§½¨ÉèеÄAPIÁîÅÆ£¬²¢½«Æä·µ»Ø¸ø¿Í»§¶Ë¡£
²âÊÔAPIÉí·ÝÑéÖ¤
ÏÖÔÚ£¬ÎÒÃÇ¿ÉÒÔͨ¹ý·¢ËÍÓû§ÃûºÍÃÜÂëÀ´²âÊÔAPIÉí·ÝÑéÖ¤¡£¿ÉÒÔʹÓÃPostman»òcurlµÈ¹¤¾ßÖ´ÐÐÒÔÏÂÏÂÁ
curl -X POST http://your-app-url/api/login -H 'content-type: application/json' -d '{ "email": "user@example.com", "password": "password" }'
µÇ¼ºó¸´ÖÆ
ÈôÊÇÓû§ÃûºÍÃÜÂëÊÇ׼ȷµÄ£¬½«ÊÕµ½°üÀ¨APIÁîÅ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r8D1NX1G4p9jRcI16MEFDE" }
µÇ¼ºó¸´ÖÆ
È»ºó£¬¿ÉÒÔʹÓÃÁíÒ»¸öÏÂÁîÀ´»á¼ûÐèÒªÉí·ÝÑéÖ¤µÄ·ÓÉ£º
curl -X GET http://your-app-url/api/details -H 'authorization: Bearer <token>'
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄÏÂÁîÖУ¬½« Ì滻ΪÉÏÒ»²½ÖлñµÃµÄAPIÁîÅÆ¡£ÈôÊÇÁîÅÆÓÐÓã¬Ôò½«»ñµÃÉí·ÝÑéÖ¤µÄÏìÓ¦£º
{ "user": { "id": 1, "name": "User", "email": "user@example.com", "email_verified_at": null, "created_at": "2021-08-13T02:58:04.000000Z", "updated_at": "2021-08-13T02:58:04.000000Z" } }
µÇ¼ºó¸´ÖÆ
×ܽá
ÔÚ±¾ÎÄÖУ¬ÎÒÃÇÏÈÈÝÁËÔõÑùʹÓÃLaravel PassportʵÏÖAPIÉí·ÝÑéÖ¤¡£Ê¹ÓÃLaravel Passport£¬Äú¿ÉÒÔÇáËɵØΪÄúµÄWeb APIÌíÔöÇ¿Ê¢µÄÉí·ÝÑéÖ¤Ö§³Ö£¬ÈÃÄúµÄÓû§Êý¾ÝÔ½·¢Çå¾²¡£Laravel Passport»¹ÌṩÁËÆäËûÇ¿Ê¢µÄ¹¦Ð§£¬ÈçAPI»á¼ûÁîÅÆÖÎÀíºÍOAuth2¿Í»§¶ËÖÎÀí¡£ÈôÊÇÄúÊÇLaravel¿ª·¢Õߣ¬ÇëÎñ±ØÉîÈëÏàʶLaravel Passport£¬²¢ÔÚÄúµÄÏÂÒ»¸öWebÏîÄ¿ÖÐʹÓÃËü¡£
ÒÔÉϾÍÊÇLaravel¿ª·¢£ºÔõÑùʹÓÃLaravel PassportʵÏÖAPIÉí·ÝÑéÖ¤£¿µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡