Laravel5.3 集成 jwt

  • 安装jwt包
"tymon/jwt-auth":"1.0.0-alpha.3"
  • 修改app.php
"providers"=>[
    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]

"aliases"=>[
    'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth',
]
  • 发布配置文件
php artisan vendor:publish
  • 修改auth.php

我没有使用user表作为登录的表,因此下面的写法更具有普遍性。

    'guards' => [
        'api' => [
            'driver' => 'jwt',
            'provider' => 'members',
        ],
    ],

    'providers' => [
        'members' => [
            'driver' => 'eloquent',
            'model' => App\Models\Member::class,
        ],
    ],
  • 不使用默认的登录控制器,新建控制器并重写AuthenticatesUsers的方法。因为laravel自带的用于后台了。
class AuthController extends ApiController
{
    use AuthenticatesUsers;

    protected function guard()
    {
        return Auth::guard("api");
    }

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required', 'password' => 'required',
        ],[
            "required"=>"msg"
        ]);
    }

    protected function sendFailedLoginResponse(Request $request)
    {
        throw new AuthenticationException("msg");
    }

    protected function sendLoginResponse(Request $request)
    {
        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user());
    }

    public function username()
    {
        return 'mobile';
    }

    public function authenticated(Request $request, $user)
    {
        $token = JWTAuth::fromUser($user);
        return response()->json([
            'token' => $token,
        ]);
    }

    public function login(Request $request)
    {
        $this->validateLogin($request);
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        $credentials = $this->credentials($request);

        if ($this->guard()->attempt($credentials)) {
            return $this->sendLoginResponse($request);
        }
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }
    public function logout()
    {
        $this->guard()->logout(); 
    }
}
  • 中间件以及routes/api.php

api使用了dingo/api构建

 $v2_namespace = "自己定义";
$api->version("v2",['prefix' => 'api/v2', 'namespace' => $v2_namespace],function(\Dingo\Api\Routing\Router $api){
    /**
     * 登录和退出登录
     */
    $api->post("login","AuthController@login");
    $api->post("logout","AuthController@logout");

    /**
     * 测试
     */
    $api->group(["middleware"=>"auth:api"],function (\Dingo\Api\Routing\Router $api){
        $api->get("test/token","TestController@testToken");
    });
});

备注

TestController实现

class TestController extends ApiController 
{
    public function testToken()
    {
        $user = JWTAuth::parseToken()->authenticate();

        return $user->toArray();
    }
}

url

http://localhost/api/v2/test/token

header

Authorization Bearer {token}

更多请参考

https://github.com/tymondesigns/jwt-auth/issues/860  
https://github.com/tymondesigns/jwt-auth/issues/260#issuecomment-143683226

谢谢观看。

轮回几多到凡尘,轮回几多少一人。
本帖已被设为精华帖!
本帖由系统于 6年前 自动加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 6

为啥要用这个版本呢1.0.0-alpha.3,
现在不是都用5.0.*版本吗

7年前 评论

@igo9go 5.3 需要1.0 以上的版本

7年前 评论

有完整的代码吗?发我!我的报错 dmk@umxnt.com

7年前 评论

想问问 不是api 么? 不用返回validate 信息么?

6年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!