Laravel使用JWT来创建用户认证API

本文来自pilishen.com----原文链接; 欢迎作客我们的php&Laravel学习群:109256050

这个例子将引导你在laravel中使用JWT来创建用户登录和注册的API。JWTJson Web Token的简称,可以帮助我们创建用户认证,以此连接前后端。

(一)安装tymon/jwt-auth组件

composer require tymon/jwt-auth

修改config/app.php

'providers' => [
    ....
    'Tymon\JWTAuth\Providers\JWTAuthServiceProvider',
],
'aliases' => [
    ....
    'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth'
],

发布JWT的配置文件,用以修改token过期时间等:

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"

生成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 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

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":"[email protected]","password":"123456"},
    success: function (data) {
        alert("user created successfully")
    }
});

测试Login API:

$.ajax({
    url: "//learnl52.hd/api/login",
    dataType: "json",
    type: "POST",
    data: {"email":"[email protected]","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)
    }
});

相关推荐