Laravel¿ª·¢£ºÔõÑùʹÓÃLaravel SanctumʵÏÖSPAºÍAPIÉí·ÝÑéÖ¤£¿
laravel sanctumÊÇÒ»¸öÇáÁ¿¼¶µÄÉí·ÝÑéÖ¤°ü£¬Äܹ»ÈÃÄãÔÚlaravelÓ¦ÓÃÖÐÇáËɵØʵÏÖapiÈÏÖ¤ºÍspa£¨µ¥Ò³Ó¦ÓóÌÐò£©ÈÏÖ¤¡£ÔÚ±¾ÎÄÖУ¬ÎÒÃǽ«Ì½ÌÖÔõÑùʹÓÃlaravel sanctumÀ´ÊµÏÖspaºÍapiÉí·ÝÑéÖ¤¡£
Ê×ÏÈ£¬ÈÃÎÒÃÇ¿´¿´Ê²Ã´ÊÇSPAºÍAPIÈÏÖ¤¡£
SPAÈÏÖ¤ÊÇÖ¸µ¥Ò³Ó¦ÓóÌÐò£¬Ëü²»»áÖØмÓÔØÕû¸öÒ³Ã棬¶øÊÇʹÓÃAJAX´ÓWebЧÀÍÆ÷ÇëÇóÐÅÏ¢£¬ÒԴ˸üоֲ¿ÄÚÈÝ¡£µ±Ê¹ÓÃSPAʱ£¬ÐèÒª¶ÔAPI¾ÙÐÐÉí·ÝÑéÖ¤£¬ÒÔÈ·±£Ö»ÓоÓÉÉí·ÝÑéÖ¤µÄÓû§²Å»ª»á¼ûËüÃÇ¡£
APIÈÏÖ¤ÊÇÖ¸APIÇëÇóÉí·ÝÑéÖ¤Àú³Ì¡£µ±¿Í»§¶Ë·¢ËÍÇëÇóʱ£¬APIÐèÒªÑéÖ¤¸ÃÇëÇóÊÇ·ñÀ´×ÔËùÆÚÍûµÄÓû§£¬ÒÔ´Ë°ü¹ÜAPI¶Ëµã½öÓɾÓÉÉí·ÝÑéÖ¤µÄÓû§Ê¹Óá£
ÏÂÃæÊÇÔõÑùʹÓÃLaravel SanctumʵÏÖSPAºÍAPIÉí·ÝÑéÖ¤µÄ°ì·¨£º
1¡¢×°ÖÃLaravel Sanctum
ÎÒÃÇ¿ÉÒÔʹÓÃcomposer°ü¹ÜÀíÆ÷×°ÖÃLaravel Sanctum¡£ÔÚLaravelÏîÄ¿ÖÐÔËÐÐÒÔÏÂÏÂÁ
composer require laravel/sanctum
µÇ¼ºó¸´ÖÆ
2¡¢ÔËÐÐLaravel SanctumµÄ×°ÖÃÆ÷
Laravel SanctumÌṩÁËÒ»¸ö×°ÖÃÆ÷£¬¿ÉÒÔÔÚ×°ÖÃʱ×Ô¶¯ÉèÖÃÎÒÃǵÄÓ¦ÓóÌÐò¡£ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÔËÐдË×°ÖÃÆ÷£º
php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"
µÇ¼ºó¸´ÖÆ
3¡¢ÔËÐÐǨáã
ÎÒÃÇÐèÒªÔËÐÐSanctumǨáãÀ´½¨ÉèÐëÒªµÄÊý¾Ý¿â±í£¬ÒÔÖ§³ÖSanctumµÄ²Ù×÷¡£ÔËÐÐÒÔÏÂÏÂÁ
php artisan migrate
µÇ¼ºó¸´ÖÆ
4¡¢ÉèÖÃÓ¦ÓóÌÐò
ÎÒÃÇÐèÒª½«Laravel SanctumÌí¼Óµ½ÎÒÃǵÄÖÐÐļþ¿ÍÕ»ÖУº
'api' => [ 'middleware' => ['auth:sanctum'], 'throttle:60,1', 'prefix' => 'api', 'namespace' => 'AppHttpControllersAPI', ],
µÇ¼ºó¸´ÖÆ
5¡¢ÎªÓû§½ÒÏþÉí·ÝÑéÖ¤ÁîÅÆ
ÔÚLaravel SanctumÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃtokenCanÒªÁì¼ì²éÁîÅÆÊÇ·ñ¾ßÓÐÌض¨µÄAPIȨÏÞ¡£ÎÒÃÇ¿ÉÒÔʹÓÃcreateTokenÒªÁìΪÓû§½ÒÏþÉí·ÝÑéÖ¤ÁîÅÆ£º
use IlluminateHttpRequest; /** * Store a newly created resource in storage. * * @param IlluminateHttpRequest $request * @return IlluminateHttpResponse */ public function store(Request $request) { $user = User::find(1); $token = $user->createToken('token-name', ['server:update'])->plainTextToken; return response()->json([ 'access_token' => $token, 'token_type' => 'Bearer', ]); }
µÇ¼ºó¸´ÖÆ
Õ⽫ΪÓû§½¨ÉèÒ»¸öÃûΪ¡®token-name¡¯µÄÁîÅÆ£¬¸ÃÁîÅƾßÓÐserver:updateȨÏÞ¡£
6¡¢±£»¤API¶Ëµã
ÔÚÎÒÃǵĿØÖÆÆ÷ÖУ¬ÎÒÃÇ¿ÉÒÔʹÓá°middleware¡±ÒªÁìÀ´±£»¤API¶Ëµã£º
public function update(Request $request, $id) { if (!$request->user()->tokenCan('server:update')) { abort(403, 'Unauthorized'); } // Update the server }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃÇÖ»ÔÊÐíÄÇЩ¾ßÓÐserver:updateȨÏÞµÄÓû§»á¼ûupdateÒªÁì¡£
7¡¢ÔÚSPAÖÐʹÓÃÉí·ÝÑéÖ¤ÁîÅÆ
ÔÚÎÒÃǵÄSPAÖУ¬ÎÒÃÇ¿ÉÒÔʹÓÃSanctumµÄ@authºÍ@csrf BladeÖ¸ÁîÀ´»ñÈ¡Éí·ÝÑéÖ¤ÁîÅÆ£º
<head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet"> <script src="{{ asset('js/app.js') }}" defer></script> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> <!-- Meta --> <meta name="csrf-token" content="{{ csrf_token() }}"> </head> <body> <div id="app"> <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm"> <div class="container-fluid"> <a class="navbar-brand" href="{{ url('/') }}"> {{ config('app.name', 'Laravel') }} </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <!-- Left Side Of Navbar --> <ul class="navbar-nav mr-auto"> </ul> <!-- Right Side Of Navbar --> <ul class="navbar-nav ml-auto"> <!-- Authentication Links --> @guest <li class="nav-item"> <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a> </li> @if (Route::has('register')) <li class="nav-item"> <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a> </li> @endif @else <li class="nav-item dropdown"> <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre> {{ Auth::user()->name }} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> {{ __('Logout') }} </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> @csrf </form> </div> </li> @endguest </ul> </div> </div> </nav> <main class="py-4"> @yield('content') </main> </div> @auth <script> window.Laravel = {!! json_encode([ 'csrf_token' => csrf_token(), 'api_token' => Auth::user()->api_token ]) !!}; </script> @endauth </body>
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃÇʹÓÃÁËSanctumµÄ@authºÍ@csrf BladeÖ¸ÁÓÃÓÚ»ñÈ¡Óû§Éí·ÝÑéÖ¤ÁîÅƺÍCSRFÁîÅÆ¡£
Õâ¾ÍÊÇÔõÑùʹÓÃLaravel SanctumʵÏÖSPAºÍAPIÉí·ÝÑéÖ¤µÄËùÓÐÄÚÈÝ¡£Ê¹ÓÃLaravel Sanctum¿ÉÒÔÇáËɵر£»¤ÎÒÃǵÄAPI¶ËµãºÍSPAÓ¦ÓóÌÐò£¬²¢×ÊÖúÎÒÃÇʵÏÖ×î¼ÑÇ徲ʵ¼ù¡£
ÒÔÉϾÍÊÇLaravel¿ª·¢£ºÔõÑùʹÓÃLaravel SanctumʵÏÖSPAºÍAPIÉí·ÝÑéÖ¤£¿µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡