laravel5.5 集成JWT

laravel5.5集成JWT

1、安装

地址:https://github.com/tymondesigns/jwt-auth

文档:http://jwt-auth.readthedocs.io/en/develop/quick-start/#authenticated-requests

安装前需要执行迁移文件:

php artisan migrate

users表创建出来。

如果出错可能是编码格式的问题,修改 config/database.php 红色部分:

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

下载jwt命令:

提示:没有安装 composer 的可以去看本博客教程,或者直接添加到 conposer.json 里在 composer uptate 也可以:

composer require tymon/jwt-auth dev-develop

或者:

composer require tymon/jwt-auth 1.0.0-rc.1

2、添加服务提供者到 providers 数组中,在config/app.php

Tymon\JWTAuth\Providers\LaravelServiceProvider::class,

3、添加 JWTAuth 门面 和 JWTFactory 门面

'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,

4、发布相应配置文件,发布后你可以在 config/jwt.php 中配置

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

5、最后一步需要生成 JWT Key

php artisan jwt:secret

注意这里如果之前有生成过,会提示你是否覆盖 输入yes即可!

6、你的 App/user.php model 需要修改成这样(注意红色部分):

<?php

namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
    /**
     * 获取将存储在JWT主题声明中的标识符。
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * 返回一个键值数组,其中包含要添加到JWT的任何自定义声明。
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

7、创建一个 UserController 

php artisan make:controller UserController

修改内容:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;


class UserController extends Controller
{
    public function getToken(Request $request)
    {
        $request->validate([
            'name'     => 'required|min:1|max:255',
            'password' => 'required|min:6|max:255'
        ]);

        if (! $token = JWTAuth::attempt($request->all())) {
            return response(['error' => 'Account or password error.'], 400);
        }

        return $this->setAuthenticationHeader($token);
    }
    public function me(Request $request)
    {
        
        $user  = $request->user();
       return response()->json(['success' => true, 'message' => $user]);
    }
    /**
     * Set the authentication header.
     *
     * @param  \Illuminate\Http\Response|\Illuminate\Http\JsonResponse  $response
     * @param  string|null  $token
     *
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     */
    protected function setAuthenticationHeader($token = null)
    {
        $token = $token ?: $this->auth->refresh();
        
        return response()->json(['success' => true], 200)->header('Authorization', 'Bearer ' . $token);//注意'Bearer '这里有一个空格 
  }
}

8、创建中间件 api.jwt.auth

命令:

php artisan make:middleware ApiJwtAuth

编辑 App\Http\Middleware\ApiJwtAuth.php:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\JWTAuth;

class ApiJwtAuth
{
    /**
     * @var \Tymon\JWTAuth\JWTAuth
     */
    protected $auth;
    /**
     * Create a new BaseMiddleware instance.
     *
     * @param \Tymon\JWTAuth\JWTAuth  $auth
     */
    public function __construct(JWTAuth $auth)
    {
        $this->auth = $auth;
    }
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (! $this->auth->parser()->setRequest($request)->hasToken()) {
            return $this->respond('token_not_provided', 422); //缺少令牌
        }
        try {
            if (!$user = $this->auth->parseToken()->authenticate()) {
                return $this->respond('user_not_found', 404);
            }
        } catch (TokenExpiredException $e) {
            return $this->respond('token_expired', 401); //令牌过期
        } catch (JWTException $e) {
            return $this->respond('token_invalid', 400); //令牌无效
        }

        return $next($request);
    }
    /**
     * Fire event and return the response.
     *
     * @param  string   $error
     * @param  int      $status
     * @return mixed
     */
    protected function respond($error, $status)
    {
        return response()->json(['error' => $error], $status);
    }
}

注册该中间件在 app/Http/Kernel.php

namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
    ...
    ...
    protected $routeMiddleware = [
        ...
        'api.jwt.auth' => \App\Http\Middleware\ApiJwtAuth::class, 
  ];
}

9、创建路由在 routes/api.php

Route::post('register', 'UserController@register');// 注册
Route::post('login', 'UserController@login');// 获取token
Route::group(['middleware' => 'api.jwt.auth'], function () {
    Route::get('me', 'UserController@me');  // 获取用户详情
});

你也可以不需要注册中间件直接使用 jwt.auth 自带的中间件

Route::post('register', 'UserController@register');     // 注册
Route::post('login', 'UserController@login');           // 登陆
Route::group(['middleware' => 'jwt.auth'], function () {
    Route::post('get_user_details', 'UserController@get_user_details');  // 获取用户详情
});

10、用 postman 进行测试

注册:

 登录后的token信息在header 里,在请求其他的接口是必须带上

 

email 登陆:

1.修改 UserControoler

 

        $request->validate([
            'emial'     => 'required|min:1|max:255',
            'password' => 'required|min:6|max:255'
        ]);

 

获取用户信息:

 

 

posted @ 2017-09-21 10:52  丶老中医  阅读(1095)  评论(0编辑  收藏  举报
一切已经开始©2018 丶老中医