Cara Wang <caraw@cnyes.com>
@author Cara Wang <caraw@cnyes.com>
@since 2017/03/28
php artisan make:auth
php artisan serve
php artisan make:auth
php artisan serve
php artisan migrate
如果你使用 Laravel 5.4 + MySQL 5.6 或以下版本
namespace App\Providers;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Schema::defaultStringLength(191);
}
}
Ref: https://laravel-news.com/laravel-5-4-key-too-long-error
1|EWnGacWd8GnEUVdeeki0GLs70tjJCfb9jph2LkAbvkdTq0e8SHhA2L8mUWb0
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
...
public function apiRegister(Request $request)
{
$data = $request->json()->all();
$this->validator($data)->validate();
$data['token'] = str_random(20);
$user = $this->create($data);
return response()->json(['token' => $data['token']]);
}
// 1. install package
composer require tymon/jwt-auth
// 2. modify config/app.php
'providers' => [
Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
],
'aliases' => [
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
],
// 3. setup config
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
php artisan jwt:generate
namespace App\Http\Controllers\Auth;
use JWTAuth;
use Illuminate\Http\Request;
class LoginController extends Controller
{
public function apiLogin(Request $request)
{
$data = $request->json()->all();
$token = JWTAuth::attempt($data);
if (!$token) {
return response()->json(['error' => 'Invalid User']);
}
return response()->json(['token' => $token]);
}
}
// route/api.php
Route::post('/login', 'Auth\LoginController@apiLogin');
namespace App\Exceptions;
class Handler extends ExceptionHandler
{
public function render($request, Exception $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => $exception->getMessage()], 500);
}
return parent::render($request, $exception);
}
}
// route/api.php
use Tymon\JWTAuth\Facades\JWTAuth;
Route::middleware('jwt')->get('/user', function (Request $request) {
return JWTAuth::parseToken()->toUser();
});
php artisan make:middleware JWTAuthentication
namespace App\Http\Middleware;
use JWTAuth;
class JWTAuthentication
{
public function handle($request, Closure $next)
{
JWTAuth::parseToken()->authenticate();
return $next($request);
}
}
namespace App\Http;
class Kernel extends HttpKernel
{
protected $routeMiddleware = [
'jwt' => \App\Http\Middleware\JWTAuthentication::class
];
}
// route/api.php
Route::get('/refresh', 'Auth\LoginController@refreshToken');
public function refreshToken()
{
$newToken = JWTAuth::parseToken()->refresh();
return response()->json(['token' => $newToken]);
}