• Laravel 使用 JWT 做 API 认证之tymon/jwt-auth 1.0.0-beta.1实践


    安装

    "tymon/jwt-auth": "1.0.0-beta.1" 添加到 composer.json 中,执行 composer update

    Providers

    config/app.php 中在 providers 里添加 TymonJWTAuthProvidersLaravelServiceProvider::class,

    Class Aliases

    config/app.php 中在 aliases 里添加 'JWTAuth' => TymonJWTAuthFacadesJWTAuth::class

    修改认证驱动

    修改config/auth.php,将 api 的 driver 修改为 jwt。如下:

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

    添加路由

    在 routes/api.php 中添加以下路由:

    $api = app('DingoApiRoutingRouter');
    
    $api->version('v1', ['namespace' => 'AppHttpControllersApiV1'], function($api) {
        $api->post('token', 'UserController@token');    //获取token
        $api->post('refresh-token', 'UserController@refershToken'); //刷新token
    
        $api->group(['middleware' => ['auth:api']], function($api) {
            $api->post('logout', 'UserController@logout');    //登出
            $api->get('me', 'UserController@me');    //关于我
        });
    
    });

    AppUser.php

    添加 getJWTIdentifier 和 getJWTCustomClaims 实现 AuthenticatableUserContract

    <?php
    
    namespace AppModels;
    
    use IlluminateNotificationsNotifiable;
    use IlluminateFoundationAuthUser as Authenticatable;
    use TymonJWTAuthContractsJWTSubject as AuthenticatableUserContract;
    
    class User extends Authenticatable implements AuthenticatableUserContract
    {
    
    
        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];
    
        /**
         * @return mixed
         */
        public function getJWTIdentifier()
        {
            return $this->getKey(); // Eloquent model method
        }
    
        /**
         * @return array
         */
        public function getJWTCustomClaims()
        {
            return [];
        }
    
    }
    

    实现路由所需要的控制器

    <?php
    
    namespace AppHttpControllersApiV1;
    
    use AppHttpControllersApiV1Controller;
    use AppModelsUser;
    use IlluminateHttpRequest;
    use TymonJWTAuthExceptionsJWTException;
    use Auth;
    
    class UserController extends Controller
    {
    
        protected $guard = 'api';
    
        /**
         * 获取token
         *
         * @param Request $request
         * @return IlluminateHttpJsonResponse
         */
        public function token(Request $request)
        {
            $credentials=[
                'email' => $request->email,
                'password'  => $request->password,
                'status' => 0,
            ];
    
            try {
                if (! $token = Auth::guard($this->guard)->attempt($credentials)) {
                    return response()->json(['error' => 'invalid_credentials'], 401);
                }
            } catch (JWTException $e) {
                return response()->json(['error' => 'could_not_create_token'], 500);
            }
    
            return response()->json(compact('token'));
        }
    
        /**
         * @return mixed
         */
        public function refershToken()
        {
            $token = Auth::guard($this->guard)->refresh();
    
            return $this->response->array(compact('token'));
        }
    
        /**
         * 个人信息
         *
         * @return User|null
         */
        public function me()
        {
            return Auth::guard('api')->user();
        }
    
        /**
         * 退出
         *
         * @return IlluminateHttpJsonResponse
         */
        public function logout()
        {
            Auth::guard($this->guard)->logout();
            return response()->json(['status' => 'ok']);
        }
    }

    原文地址
    http://moell.cn/article/37

  • 相关阅读:
    多线程(一) NSThread
    Swift 烧脑体操(一)
    Swift 烧脑体操(二)
    UINavigationController使用的注意事项
    更多请查看我的文章
    本地通知
    网络编程(二)NSURLSessionConfiguration
    A
    51Nod 1116 K进制下的大数(暴力枚举)
    51Nod 1065 最小正子段和
  • 原文地址:https://www.cnblogs.com/wzjwffg/p/9882717.html
Copyright © 2020-2023  润新知