laravelÖÐjwtÔõôÓÃ
Ëæ×ÅapiµÄÒ»Ö±Éú³¤£¬Ô½À´Ô½¶àµÄwebÓ¦ÓóÌÐòÐèҪʹÓÃjson web tokens£¨jwt£©À´ÊµÏÖÓû§ÈÏÖ¤ºÍÊÚȨ¡£¶ølaravel×÷Ϊһ¸ö¿ª·¢apiµÄÊ×Ñ¡¿ò¼Ü£¬Ò²Ö§³Öjwt¡£±¾ÎĽ«ÏÈÈÝÔÚlaravelÖÐÔõÑùʹÓÃjwt¡£
ʲôÊÇJWT£¿
JSON Web Token£¨JWT£©ÊÇÒ»ÖÖ¿ª·Å±ê×¼£¨RFC 7519£©£¬ÓÃÓÚÔÚ¸÷·½Ö®¼äÇå¾²µØ½«ÉùÃ÷´«ÊäΪJSON¹¤¾ß¡£JWT¿ÉÒÔÓÃÓÚÊÚȨ¡¢Éí·ÝÑéÖ¤ºÍÐÅÏ¢½»Á÷¡£JWTͨ³£ÔÚHTTPÇëÇóµÄAuthorizationÍ·ÖÐ×÷ΪBearerÁîÅÆ´«Êä¡£
JWTµÄ½á¹¹ÓÉÈý²¿·Ö×é³É£ºÍ·²¿¡¢ÔغɺÍÊðÃû¡£Í·²¿ºÍÔغɶ¼ÊÇJSON¹¤¾ß£¬ÊðÃûÊǽ«ÕâÁ½¸ö²¿·ÖÍŽáÆðÀ´¼ÓÃܵÄЧ¹û¡£ÓÉÓÚJWTµÄ½á¹¹ºÜÊǼòÆÓ£¬Òò´Ë¿ÉÒÔÇáËɵØÆÊÎöºÍÑéÖ¤¡£
ÔõÑùÔÚLaravelÖÐʹÓÃJWT£¿
ʹÓÃJWTÐèÒªÔÚLaravelÏîÄ¿ÖÐ×°ÖÃÏÂÁÐÒÀÀµ¿â£ºtymondesigns/jwt-auth¡£ÔÚLaravel 5.7¼°¸ü¸ß°æ±¾ÖУ¬¿ÉÒÔʹÓÃÒÔÏÂÏÂÁî×°ÖøÃÒÀÀµ¿â£º
composer require tymon/jwt-auth
µÇ¼ºó¸´ÖÆ
×°ÖÃÍê³Éºó£¬ÐèÒªÔÚconfig/app.phpÎļþÖÐÌí¼ÓÒÔÏÂЧÀÍÌṩ³ÌÐòºÍÓÖÃû£º
'providers' => [ // Other Service Providers TymonJWTAuthProvidersLaravelServiceProvider::class, ], 'aliases' => [ // Other Aliases 'JWTAuth' => TymonJWTAuthFacadesJWTAuth::class, 'JWTFactory' => TymonJWTAuthFacadesJWTFactory::class, ],
µÇ¼ºó¸´ÖÆ
½ÓÏÂÀ´£¬ÐèÒªÌìÉúJWTµÄÃÜÔ¿¡£¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÌìÉúÃÜÔ¿£º
php artisan jwt:secret
µÇ¼ºó¸´ÖÆ
Õâ¸öÏÂÁî»áÌìÉúÒ»¸öËæ»úµÄÃÜÔ¿£¬²¢½«ÆäÌí¼Óµ½config/jwt.phpÎļþÖС£ºÜÖ÷ÒªµÄÒ»µãÊÇ£¬ÐèÒª±£»¤ºÃ¸ÃÃÜÔ¿£¬²»Òª½«Æäй¶¸øÈκÎÈË¡£
ÌìÉúÃÜÔ¿ºó£¬¿ÉÒÔ×îÏÈÔÚLaravelÖÐʹÓÃJWT¡£JWT¿ÉÒÔÓÃÓÚÉí·ÝÑéÖ¤ºÍÊÚȨ¡£
ʹÓÃJWT¾ÙÐÐÉí·ÝÑéÖ¤
ÔÚLaravelÖÐʹÓÃJWT¾ÙÐÐÉí·ÝÑéÖ¤µÄÀú³ÌÈçÏ£º
Óû§Ìá½»Æäƾ֤£¨ÀýÈ磬Óû§ÃûºÍÃÜÂ룩¡£
Ó¦ÓóÌÐòʹÓÃÕâЩƾ֤À´ÌìÉúÒ»¸öJWT£¬²¢½«Æä·µ»Ø¸øÓû§¡£
Óû§ÔÚ½ÓÏÂÀ´µÄÇëÇóÖн«¸ÃJWT°üÀ¨ÔÚAuthorizationÍ·ÖУ¬×÷ΪBearerÁîÅÆ¡£
Ó¦ÓóÌÐò´ÓJWTÖÐÌáÈ¡Óû§ÐÅÏ¢£¬²¢ÑéÖ¤ÆäÉí·Ý¡£
ÌìÉúJWT²¢·µ»Ø¸øÓû§µÄ´úÂëÈçÏ£º
public function login(Request $request) { $credentials = $request->only('email', 'password'); if (!$token = JWTAuth::attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } return response()->json(['token' => $token]); }
µÇ¼ºó¸´ÖÆ
ÑéÖ¤JWT²¢ÌáÈ¡Óû§ÐÅÏ¢µÄ´úÂëÈçÏ£º
public function profile(Request $request) { $user = JWTAuth::parseToken()->authenticate(); return response()->json(['user' => $user]); }
µÇ¼ºó¸´ÖÆ
ʹÓÃJWT¾ÙÐÐÊÚȨ
ÔÚLaravelÖÐʹÓÃJWT¾ÙÐÐÊÚȨµÄÀú³ÌÈçÏ£º
Ó¦ÓóÌÐòÔÚÓû§»á¼ûÊܱ£»¤µÄ×ÊԴ֮ǰ£¬ÑéÖ¤ÆäÉí·Ý¡£
ÈôÊÇÓû§ÒѾͨ¹ýÉí·ÝÑéÖ¤£¬ÔòÓ¦ÓóÌÐò¼ì²é¸ÃJWTÊÇ·ñ°üÀ¨Êʵ±µÄ½ÇÉ«»òȨÏÞ¡£
ÈôÊÇÓû§ÓµÓÐÊʵ±µÄ½ÇÉ«»òȨÏÞ£¬ÔòÓ¦ÓóÌÐòÊÚÓèÆä»á¼ûËùÇëÇóµÄ×ÊÔ´¡£
ÑéÖ¤JWT²¢¼ì²éÓû§µÄ½ÇÉ«»òȨÏ޵ĴúÂëÈçÏ£º
public function index(Request $request) { $user = JWTAuth::parseToken()->authenticate(); if ($user->hasRole('admin')) { $items = Item::all(); } else { $items = Item::where('user_id', '=', $user->id)->get(); } return response()->json(['items' => $items]); }
µÇ¼ºó¸´ÖÆ
ÐèҪעÖصÄÊÇ£¬ÕâÀïµÄhasRole()ÒªÁìÊÇ×Ô½ç˵ҪÁ죬ÐèÒªÔÚUserÄ£×ÓÖÐʵÏÖ¡£
×ܽá
±¾ÎÄÏÈÈÝÁËÔÚLaravelÖÐʹÓÃJWT¾ÙÐÐÉí·ÝÑéÖ¤ºÍÊÚȨµÄÀú³Ì¡£JWTÌṩÁËÒ»ÖÖÇå¾²¡¢¼òÆӺͿÉÀ©Õ¹µÄÓû§Éí·ÝÑéÖ¤»úÖÆ£¬Äܹ»±£»¤Ó¦ÓóÌÐòÃâÊÜÖÖÖÖ¹¥»÷¡£ÈôÊÇÄãÕýÔÚ¿ª·¢Ò»¸öÐèÒªAPIµÄWebÓ¦ÓóÌÐò£¬ÄÇôʹÓÃJWTÊÇÒ»¸ö²»´íµÄÑ¡Ôñ¡£
ÒÔÉϾÍÊÇlaravelÖÐjwtÔõôÓõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡