laravel 5.4 + dingo api + jwt 代替

作者: guanguans | 来源:发表于2018-03-20 15:29 被阅读94次

    前言

    由于在度娘找了半天根本一大堆Copy版本,弄得我死去活来的,每个都试了一堆问题,到底你们做完有没有总结过一次?然后有几个使用lunmen+dingo api+jwt,完全不行啊,太监版不是我想要的。
    后来Google,终于找到例子并实测成功。直接来了

    新装一个LV

    composer create-project --prefer-dist laravel/laravel myApiProject
    

    安装dingo api

    在composer.json中添加

    composer require dingo/api:1.0.x@dev
    

    config/app.php

     'providers' => [
         //前面很多
        Dingo\Api\Provider\LaravelServiceProvider::class,
    ]
    

    发布配置文件
    终端运行

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

    打开.env文件,把dingo的配置放到最后面

    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 // 调试模式
    

    下面是我的配置:

    API_STANDARDS_TREE=vnd
    API_SUBTYPE=emall
    API_PREFIX=api
    API_VERSION=v1
    
    

    没必要每个都配上去,主要的配一下就可以了

    安装jwt

    还是composer.json

    "require-dev": {
        "tymon/jwt-auth": "1.0.*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true 
    

    其实只需要加上,下面是我的写法,上面是国外的写法

       "tymon/jwt-auth": "1.0.*@dev"
    

    运行composer update将dingo和jwt装上去

    添加jwt的认证
    config/api.php添加内容

    'auth' => [
        'jwt' => Dingo\Api\Auth\Provider\JWT::class
    ]
    

    config/app.php

    'providers' => [
        // 前面很多
        Tymon\JWTAuth\Providers\LaravelServiceProvider::class
    ],
    
    'aliases' => [
        // 前面很多
        'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class
    ]
    

    在终端运行:

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

    会生成config/jwt.php 这是jwt的配置文件

    生成jwtkey.env文件运行:

    php artisan jwt:secret
    

    路由

    routers/api.php
    中新建内容,两个路径分别是注册和登录:

    //这句接管路由
    $api = app('Dingo\Api\Routing\Router');
    
    $api->version('v1', function ($api) {
    
     $api->post('login', 'App\Http\Controllers\Api\Auth\LoginController@login');
     $api->post('register', 'App\Http\Controllers\Api\Auth\RegisterController@register');
    
    }); 
    

    生成两个controller
    终端输入:

    php artisan make:controller App\\Http\\Api\\Auth\\LoginController
    php artisan make:controller App\\Http\\Api\\Auth\\RegisterController  
    

    数据库

    备置.env文件

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=databasename
    DB_USERNAME=root
    DB_PASSWORD=
    

    添加迁移文件,当然你也可以使用php artisan make:auth 安装LV自带的用户
    下面我们用新建的吧
    终端运行:

    php artisan make:model User -m 
    

    此命令可以添加迁移文件同时添加Model
    迁移文件一般在database/migrations/时间格式_create_users_table.php
    打开迁移文件修改以下内容:

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
    

    终端运行:php artisan migrate创建users

    打开我们新建的ModelApp/User.php
    添加如下内容:

    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Tymon\JWTAuth\Contracts\JWTSubject;
    
    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',
        ];
    
        /**
         * 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 [];
        }
    }
    
    

    注册

    在之前建的App/Http/Controller/Api/Auth/RegisterController.php
    添加如下内容:

    use App\Http\Controllers\Controller;
    use App\User;
    use Dingo\Api\Exception\StoreResourceFailedException;
    use Dingo\Api\Routing\Helpers;
    use Illuminate\Foundation\Auth\RegistersUsers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Validator;
    use Tymon\JWTAuth\Facades\JWTAuth;
    
    class RegisterController extends Controller
    {
        use RegistersUsers;
        use Helpers;
    
        public function register(Request $request){
    
            $validator = $this->validator($request->all());
            if($validator->fails()){
                throw new StoreResourceFailedException("Validation Error", $validator->errors());
            }
    
            $user = $this->create($request->all());
    
            if($user->save()){
    
                $token = JWTAuth::fromUser($user);
    
                return $this->response->array([
                    "token" => $token,
                    "message" => "User created",
                    "status_code" => 201
                ]);
            }else{
                return $this->response->error("User Not Found...", 404);
            }
        }
    
        protected function validator(array $data)
        {
            return Validator::make($data, [
                'name' => 'required|unique:users',
                'email' => 'required|email|max:255|unique:users',
                'password' => 'required|min:6',
            ]);
        }
    
        protected function create(array $data)
        {
            return User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
            ]);
        }
    
    }
    
    

    打开Postman进行测试地址:http://127.0.0.1/myApiProject...

    [图片上传失败...(image-e47af2-1521530944954)]

    登录

    在之前建的App/Http/Controller/Api/Auth/LoginController.php

    use App\User;
    use Dingo\Api\Routing\Helpers;
    use Illuminate\Foundation\Auth\AuthenticatesUsers;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\Hash;
    use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
    use Tymon\JWTAuth\Facades\JWTAuth;
    
    class LoginController extends Controller
    {
        use AuthenticatesUsers;
        use Helpers;
    
        public function login(Request $request){
    
            $user = User::where('email', $request->email)->orWhere('name', $request->email)->first();
    
            if($user && Hash::check($request->get('password'), $user->password)){
                $token = JWTAuth::fromUser($user);
                return $this->sendLoginResponse($request, $token);
            }
    
            return $this->sendFailedLoginResponse($request);
        }
    
        public function sendLoginResponse(Request $request, $token){
            $this->clearLoginAttempts($request);
    
            return $this->authenticated($token);
        }
    
        public function authenticated($token){
            return $this->response->array([
                'token' => $token,
                'status_code' => 200,
                'message' => 'User Authenticated'
            ]);
        }
    
        public function sendFailedLoginResponse(){
            throw new UnauthorizedHttpException("Bad Credentials");
        }
    
        public function logout(){
            $this->guard()->logout();
        }
     }
    
    

    打开Postman进行测试地址:http://127.0.0.1/myApiProject...

    [图片上传失败...(image-ad9ae9-1521530944954)]

    可以看到我们得到了token

    拉取用户信息

    routers/api.php添加

    $api->group(['middleware' => 'api.auth'], function ($api) {
        $api->get('user', 'App\Http\Controllers\Api\UsersController@index');
    });
    

    终端运行:

    php artisan make:controller App\\Http\\Controllers\\Api\\UsersController
    

    UsersController.php中添加

    namespace App\Http\Controllers\Api;
    
    use Dingo\Api\Routing\Helpers;
    use Illuminate\Routing\Controller;
    
    class UsersController extends Controller
    {
        use Helpers;
    
        public function __construct()
        {
            $this->middleware('api.auth');
        }
        public function index(){
    //        return User::all();
            $user = $this->auth->user();
    
            return $user;
        }
    }
    

    打开Postman进行测试地址:http://127.0.0.1/myApiProject...
    注意因为我们设定了需要token才能拉取数据,所以在请求头Header
    我们添加了:Authorization :Bearer + token
    Bearer是一种token_type在源码中有提到,应该是一种标准
    [图片上传失败...(image-6775dd-1521530944954)]

    总结

    这里只提到了注册登录,但没有管理Token。


    原文链接

    相关文章

      网友评论

        本文标题:laravel 5.4 + dingo api + jwt 代替

        本文链接:https://www.haomeiwen.com/subject/ialbqftx.html