laravel + dingo api + jwt


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


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


安装dingo api

在composer.json的require字段中添加:

"dingo/api":"1.0.*@dev",

执行:composer update


config/app.php

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

发布配置文件
终端运行

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

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

2017-08-11/598d75d6b0ff1.png

下面是我的配置:


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

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



安装jwt

在composer.json的require字段中添加:

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

执行:composer update

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

'auth' => [

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

],

config/app.php


'providers' => [

   /*
    * Laravel Framework Service 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\Api\Auth\LoginController@login');  
   $api->post('register', 'App\Http\Api\Auth\RegisterController@register');

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

   $api->version('v1', ['protected' => true], function ($api) {

       // 更新用户 token
       $api->get('upToken', 'App\Http\Controllers\Api\V1\AuthenticateController@upToken');

       // 【用户】
       // 获取当前用户信息
       $api->get('me', 'App\Http\Controllers\Api\V1\UserController@me');
       // 修改当前用户信息
       $api->post('me', 'App\Http\Controllers\Api\V1\UserController@up');
   });


});

生成两个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=jwt
DB_USERNAME=root
DB_PASSWORD=

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


php artisan make:model User -m

此命令可以添加迁移文件同时添加Model 
迁移文件一般在database/migrations/时间格式_create_users_table.php

终端运行:

php artisan make:migration create_users_table

有就不用改了,直接运行下一个命令即可

打开迁移文件修改以下内容:


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


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

<?php

namespace App;


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

class User extends Authenticatable implements JWTSubject
{

   /**
    * 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 
添加如下内容:

<?php

namespace App\Http\Api\Auth;

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){

           $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']),
       ]);
   }

}

终端运行:

php artisan serve

打开Postman进行测试地址

localhost:8000/api/register

2017-08-11/598d78bee007c.png

登录

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

<?php

namespace App\Http\Api\Auth;

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){
       //return 111111;
     /*  $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);*/

       $credentials = $request->only('email', 'password');

       try {
           // attempt to verify the credentials and create a token for the user
           if (!$token = JWTAuth::attempt($credentials)) {
               // return response()->json(['error' => 'invalid_credentials'], 401);
               return $this->response->array(['error' => 'invalid_credentials']);
           }
       } catch (JWTException $e) {
           // something went wrong whilst attempting to encode the token
           return $this->response->array(['error' => 'could_not_create_token']);
       }

       // all good so return the token
       return $this->response->array(compact('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进行测试地址

localhost:8000/api/login

2017-08-11/598d7921876f2.png

拉取用户信息

新建app/Http/Controllers/Api/V1/UserController.php

<?php

/**
* 用户控制器
*/
namespace App\Http\Controllers\Api\V1;
use Dingo\Api\Routing\Helpers;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
   use Helpers;
   /**
    * 获取用户信息
    *
    * @return mixed
    */
   public function me()
   {
       //return 1111;
       return $this->response->array($this->auth->user());
   }

   /**
    * 修改用户信息
    *
    * @return mixed
    */
   public function up()
   {
       // TODO
   }

}


打开Postman进行测试地址

localhost:8000/api/me?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwMDAvYXBpL2xvZ2luIiwiaWF0IjoxNTAyNDQxNDM4LCJleHAiOjE1MDI0NDUwMzgsIm5iZiI6MTUwMjQ0MTQzOCwianRpIjoiNUoxVnBXZm0xR0NDakJXdSIsInN1YiI6MSwicHJ2IjoiODdlMGFmMWVmOWZkMTU4MTJmZGVjOTcxNTNhMTRlMGIwNDc1NDZhYSJ9.xAfZcT_gvHyt1jCPr82KdwjHueotf79B-PSLorRUJJU

2017-08-11/598d79bc28ac2.png

总结

这里只提到了注册登录,但没有管理Token,后面有时间再写,已经用了很多上班时间。。。



雷亮博客
请先登陆后发表评论
  • 最新评论
  • 总共0条评论
  • 本站使用thinkphp搭建 © 2014-2016 www.leigougou.com 版权所有 ICP证:蜀ICP备16024789号-1
  • 联系邮箱:1031041088@qq.com