laravel5.5 dingo/api+jwt-auth

因为laravel5.5 具有发现包功能,只要包做了兼容laravel5.5就可以不用在config/app.php添加额外代码了。

集成dingo/api

github:https://github.com/dingo/api

添加

"dingo/api": "2.0.0-alpha1",

到项目下的composer.json文件的require配置项,然后

composer update

生成配置文件到config/api.php:

php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"

在.env配置文件中,设置dingo/api相关配置:

API_STANDARDS_TREE=vnd // 环境
API_SUBTYPE=myapp // 子类型
API_PREFIX=api // 前缀
API_DOMAIN=api.myapp.com //子域名  (前缀和子域名只能存在一个)
API_VERSION=v1 // 版本
API_NAME="My API" // 名字(使用API Blueprint命令才会用到)
API_CONDITIONAL_REQUEST=false // 带条件的请求
API_STRICT=false // Strict模式
API_DEFAULT_FORMAT=json // 响应格式
API_DEBUG=true // 调试模式

注意:.env配置文件是不能有空格和注释的!

dingo/api集成就完成

集成jwt教程

添加

"tymon/jwt-auth": "^1.0.0-rc.1"

到项目下的composer.json文件的require配置项,然后

composer update

然后发布微调配置文件

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

将会在config文件夹生成jwt.php文件

然后运行:

php artisan jwt:secret

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

jwt.php配置详解如下:

ttl:token有效期(分钟)
refresh_ttl:刷新token时间(分钟)
algo:token签名算法
user:指向User模型的命名空间路径
identifier:用于从token的sub中获取用户
require_claims:必须出现在token的payload中的选项,否则会抛出TokenInvalidException异常
blacklist_enabled:如果该选项被设置为false,那么我们将不能废止token,即使我们刷新了token,前一个token仍然有效
providers:完成各种任务的具体实现,如果需要的话你可以重写他们
User —— providers.user:基于sub获取用户的实现
JWT —— providers.jwt:加密/解密token
Authentication —— providers.auth:通过证书/ID获取认证用户
Storage —— providers.storage:存储token直到它们失效

至此,jwt集成就完成了。

测试dingo/api 和 jwt:

在routes/api.php文件添加:

// 接管路由
$api = app('Dingo\Api\Routing\Router');

// 配置api版本和路由
$api->version('v1', ['namespace' => 'App\Http\Api\V1\Controllers'], function ($api) {

    // 授权组
    $api->group(['prefix' => 'auth'], function ($api) {
        //$api->post('register', 'AuthenticateController@register')->name('auth.register');

        $api->post('register', 'AuthController@register');
        $api->post('login', 'AuthController@login');
        $api->post('logout', 'AuthController@logout');
        $api->post('refresh', 'AuthController@refresh');
        $api->post('me', 'AuthController@me');
        $api->get('test', 'AuthController@test');
    });

    $api->get('test/testapi', 'UserController@test')->name('test');
    $api->get('test/testjwt', 'UserController@testjwt')->name('testjwt');
    $api->get('users/{id}', 'UserController@getUserInfo')->name('getUserInfo');
});

文件路径:App\Http\Api\V1\Controllers\AuthController.php

<?php
/**
 * Date: 17/10/12
 * Time: 01:07
 */

namespace App\Http\Api\V1\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use App\User;

class AuthController extends BaseController
{

    protected $guard = 'api';//设置使用guard为api选项验证,请查看config/auth.php的guards设置项,重要!

    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login','register']]);
    }

    public function test(){
        echo "test!!";
    }

    public function register(Request $request)
    {

        $rules = [
            'name' => ['required'],
            'email' => ['required'],
            'password' => ['required', 'min:6', 'max:16'],
        ];

        $payload = $request->only('name', 'email', 'password');
        $validator = Validator::make($payload, $rules);

        // 验证格式
        if ($validator->fails()) {
            return $this->response->array(['error' => $validator->errors()]);
        }

        // 创建用户
        $result = User::create([
            'name' => $payload['name'],
            'email' => $payload['email'],
            'password' => bcrypt($payload['password']),
        ]);

        if ($result) {
            return $this->response->array(['success' => '创建用户成功']);
        } else {
            return $this->response->array(['error' => '创建用户失败']);
        }

    }

    /**
     * Get a JWT token via given credentials.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if ($token = $this->guard()->attempt($credentials)) {
            return $this->respondWithToken($token);
        }

        return $this->response->errorUnauthorized('登录失败');
    }

    /**
     * Get the authenticated User
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        //return response()->json($this->guard()->user());
        return $this->response->array($this->guard()->user());
    }

    /**
     * Log the user out (Invalidate the token)
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        $this->guard()->logout();

        //return response()->json(['message' => 'Successfully logged out']);
        return $this->response->array(['message' => '退出成功']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken($this->guard()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $this->guard()->factory()->getTTL() * 60
        ]);
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\Guard
     */
    public function guard()
    {
        return Auth::guard($this->guard);
    }
}

文件路径:App\User.php 需要implements JWTSubject

<?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',
    ];


    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

记得要在config/auth.php修改

//设置默认使用的guard,此处设置为api时,laravel 默认的auth登录则无法登录成功哦,设置为web才行
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],

好了自己慢慢消化,我也是经历很久的测试才得出的结果,未经允许请勿转载!

参考:https://github.com/tymondesigns/jwt-auth/blob/docs/docs/quick-start.md
参考:https://github.com/tymondesigns/jwt-auth/issues/1316
参考:https://moell.cn/article/37

    原文作者:HaRun
    原文地址: https://www.jianshu.com/p/62b0c4d75e59
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞