本文來自pilishen.com----原文連接; 歡迎做客咱們的php&Laravel學習羣:109256050php
這個例子將引導你在laravel中使用JWT來建立用戶登陸和註冊的API。JWT
是Json Web Token
的簡稱,能夠幫助咱們建立用戶認證,以此鏈接先後端。前端
tymon/jwt-auth
組件composer require tymon/jwt-auth
複製代碼
修改config/app.php
laravel
'providers' => [
....
'Tymon\JWTAuth\Providers\JWTAuthServiceProvider',
],
'aliases' => [
....
'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth'
],
複製代碼
發佈JWT的配置文件,用以修改token過時時間等:ajax
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
複製代碼
生成jwt的祕鑰:json
php artisan jwt:generate
複製代碼
在app/Http/routes.php
中(示例用的是laravel 5.2,你也能夠放到後期版本的api.php
中)後端
Route::group(['middleware' => ['api','cors'],'prefix' => 'api'], function () {
Route::post('register', 'APIController@register');
Route::post('login', 'APIController@login');
Route::group(['middleware' => 'jwt-auth'], function () {
Route::post('get_user_details', 'APIController@get_user_details');
});
});
複製代碼
這裏的cors
中間件,這是用來解決跨域請求默認被攔截的問題,若是不加就會有下面這個常見報錯:api
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at //test.com/api/register. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
複製代碼
因此:跨域
php artisan make:middleware CORS
複製代碼
而後在app/Http/Middleware/CORS.php
中:bash
namespace App\Http\Middleware;
use Closure;
class CORS
{
public function handle($request, Closure $next)
{
header('Access-Control-Allow-Origin: *');
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
}
}
複製代碼
註冊中間件app/Http/Kernel.php
:app
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
...
...
protected $routeMiddleware = [
...
'cors' => \App\Http\Middleware\CORS::class,
];
}
複製代碼
jwt-auth
Middlewarephp artisan make:middleware authJWT
複製代碼
而後app/Http/Middleware/authJWT.php
namespace App\Http\Middleware;
use Closure;
use JWTAuth;
use Exception;
class authJWT
{
public function handle($request, Closure $next)
{
try {
$user = JWTAuth::toUser($request->input('token'));
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
return response()->json(['error'=>'Token is Invalid']);
}else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
return response()->json(['error'=>'Token is Expired']);
}else{
return response()->json(['error'=>'Something is wrong']);
}
}
return $next($request);
}
}
複製代碼
而後app/Http/Kernel.php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
...
...
protected $routeMiddleware = [
...
'jwt-auth' => \App\Http\Middleware\authJWT::class,
];
}
複製代碼
在app/Http/Controllers/APIController.php
中:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Hash;
use JWTAuth;
class APIController extends Controller
{
public function register(Request $request)
{
$input = $request->all();
$input['password'] = Hash::make($input['password']);
User::create($input);
return response()->json(['result'=>true]);
}
public function login(Request $request)
{
$input = $request->all();
if (!$token = JWTAuth::attempt($input)) {
return response()->json(['result' => 'wrong email or password.']);
}
return response()->json(['result' => $token]);
}
public function get_user_details(Request $request)
{
$input = $request->all();
$user = JWTAuth::toUser($input['token']);
return response()->json(['result' => $user]);
}
}
複製代碼
這裏你徹底能夠使用postman
或者rest client
等其餘工具。
測試Register API:
$.ajax({
url: "//learnl52.hd/api/register",
dataType: "json",
type: "POST",
data: {"name":"HD","email":"test@gmail.com","password":"123456"},
success: function (data) {
alert("user created successfully")
}
});
複製代碼
測試Login API:
$.ajax({
url: "//learnl52.hd/api/login",
dataType: "json",
type: "POST",
data: {"email":"test@gmail.com","password":"123456"},
success: function (data) {
alert(data.result)
}
});
複製代碼
測試User Details API(這裏的token是你Login api返回的token)
$.ajax({
url: "//learnl52.hd/api/get_user_details",
dataType: "json",
type: "POST",
data: {"token":your toke here},
success: function (data) {
console.log(data)
}
});
複製代碼