Laravel使用JWT來建立用戶認證API

本文來自pilishen.com----原文連接; 歡迎做客咱們的php&Laravel學習羣:109256050php

這個例子將引導你在laravel中使用JWT來建立用戶登陸和註冊的API。JWTJson Web Token的簡稱,能夠幫助咱們建立用戶認證,以此鏈接先後端。前端

(一)安裝tymon/jwt-auth組件

composer require tymon/jwt-auth
複製代碼

修改config/app.phplaravel

'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
複製代碼

(二)建立api路由

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 Middleware

這裏的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.phpapp

namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
	...
	...
    protected $routeMiddleware = [
        ...
        'cors' => \App\Http\Middleware\CORS::class,
    ];
}
複製代碼

(四)建立jwt-auth Middleware

php 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,
    ];
}
複製代碼

(五)建立相應的Controller

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]);
    }
    
}
複製代碼

(六)前端測試API

這裏你徹底能夠使用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)
	}
});
複製代碼
相關文章
相關標籤/搜索