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

pilishen發表於2019-02-16

本文來自pilishen.com—-原文連結; 歡迎作客我們的php&Laravel學習群:109256050

這個例子將引導你在laravel中使用JWT來建立使用者登入和註冊的API。JWTJson Web Token的簡稱,可以幫助我們建立使用者認證,以此連線前後端。

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

composer require tymon/jwt-auth

修改config/app.php

`providers` => [
    ....
    `TymonJWTAuthProvidersJWTAuthServiceProvider`,
],
`aliases` => [
    ....
    `JWTAuth` => `TymonJWTAuthFacadesJWTAuth`
],

釋出JWT的配置檔案,用以修改token過期時間等:

php artisan vendor:publish --provider="TymonJWTAuthProvidersJWTAuthServiceProvider"

生成jwt的祕鑰:

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中介軟體,這是用來解決跨域請求預設被攔截的問題,如果不加就會有下面這個常見報錯:

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中:

namespace AppHttpMiddleware;
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

namespace AppHttp;
use IlluminateFoundationHttpKernel as HttpKernel;
class Kernel extends HttpKernel
{
    ...
    ...
    protected $routeMiddleware = [
        ...
        `cors` => AppHttpMiddlewareCORS::class,
    ];
}

(四)建立jwt-auth Middleware

php artisan make:middleware authJWT

然後app/Http/Middleware/authJWT.php

namespace AppHttpMiddleware;
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 TymonJWTAuthExceptionsTokenInvalidException){
                return response()->json([`error`=>`Token is Invalid`]);
            }else if ($e instanceof TymonJWTAuthExceptionsTokenExpiredException){
                return response()->json([`error`=>`Token is Expired`]);
            }else{
                return response()->json([`error`=>`Something is wrong`]);
            }
        }
        return $next($request);
    }
}

然後app/Http/Kernel.php

namespace AppHttp;
use IlluminateFoundationHttpKernel as HttpKernel;
class Kernel extends HttpKernel
{
    ...
    ...
    protected $routeMiddleware = [
        ...
        `jwt-auth` => AppHttpMiddlewareauthJWT::class,
    ];
}

(五)建立相應的Controller

app/Http/Controllers/APIController.php中:

namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppUser;
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)
    }
});

相關文章