Laravel5.4+JWT+dingo/API 构建 RESTfulAPI

环境配置

安装dingo/api和JWT

  • 通过composer require或者在项目composer.json添加required安装即可。

环境配置

  • dingo/api
    在config/app.php中的providers数组中添加 Dingo\Api\Provider\LaravelServiceProvider::class
    运行php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"发布配置
    在.env文件中添加dingo/api的相关配置。
    API_STANDARDS_TREE=vnd API_SUBTYPE=myapp API_PREFIX=api #路由前缀 API_VERSION=v1 API_DEFAULT_FORMAT=json #返回数据格式 API_DEBUG=true #开启调试
  • JWT
    将JWT的认证类加至config/api.php的auth数组中。
    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"发布。
    运行php artisan jwt:secret生成JWT的密钥。
    运行php artisan make:auth生成User

路由配置

  • routes/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('logout','App\Http\Api\Auth\LoginController@logout');
        $api->resource('user','App\Http\Api\UsersController');
    });
    $api->get('refresh','App\Http\Api\UsersController@refresh');
    });  

控制器

  • RegisterController
    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)
    {
        $valid=$this->valid($request->all());    //验证表单
        if($valid->fails()){
            $this->sendFailResponse($valid->errors());
        }
        else{
            $user=User::create([
                    'name'=>$request->name,
                    'email'=>$request->email,
                    'password'=>bcrypt($request->password)
                ]);
            if($user){
                $token=JWTAuth::fromuser($user);  //获取token
                return $this->response->array([
                    "token" => $token,
                    "message" => "Registration Success",
                    "status_code" => 201
                ]);
            }
            else{
                $this->sendFailResponse("Register Error");
            }
        }
    }
    public function valid($data)
    {
        return Validator::make($data,[
            'name'=>'required|unique:users|max:10',
            'email'=>'required|unique:users|email',
            'password'=>'required|min:6']);
    }
    public function sendFailResponse($message)
    {
        return $this->response->error($message,400);
    }
    }  
  • LoginController
    namespace App\Http\Api\Auth;
    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;
    use App\User;
    use Dingo\Api\Routing\Helpers;
    use Illuminate\Foundation\Auth\AuthenticatesUsers;
    class LoginController extends Controller
    {
    use AuthenticatesUsers;
    use Helpers;
    public function login(Request $request)
    {
        $user=User::where('name',$request->email)->orwhere('email',$request->email)->firstOrFail();
        if($user && Hash::check($request->password,$user->password)){
            $token=JWTAuth::fromuser($user);    //获取token
            $this->clearLoginAttempts($request);  //清除登录次数
            return $this->response->array([
                    'token'=>$token,
                    'message'=>"Login Success",
                    'status_code'=>200
                ]);
        }
        else{
            throw new UnauthorizedHttpException("Login Failed");        
        }
    }
    public function logout(){
        JWTAuth::invalidate(JWTAuth::getToken());    //token加入黑名单(注销)
        $this->guard()->logout();
    }
    }  
  • UserController
    GET

    public function index()
    {
        return json_encode(Test::all());
    }  

    POST

    public function store(Request $request)
    {
        //
        $valid=$this->valid($request->all());
        if($valid->fails()){
            return $this->response->error($valid->errors(),400);
        }
        else{     
            $ret=Test::create([
                    'title'=>$request->title,
                    'content'=>$request->content,
                    'tag'=>$request->tag
                ]);
            if($ret){
                return $this->sendSuccessResponse("Create Success",201);
            }
            else{
                return $this->sendFailResponse("Create Fail",500);
            }
        }
    }  

    PUT

    public function update(Request $request, $id)
    {
        //
        $data=Test::findOrFail($id);
        $valid=$this->valid($request->all());
        if($valid->fails()){
            return $this->sendFailResponse($valid->errors(),400);
        }
        else{
            $data->title=$request->title;
            $data->content=$request->content;
            $data->tag=$request->tag;
            if($data->save()){
                return $this->sendSuccessResponse("Update Success",201);
            }
            else{
                return $this->sendFailResponse("Update Fail",500);
            }
        }
    }  

    DELETE

      public function destroy($id)
    {
        //
        if(Test::destroy($id)===1){
            return $this->sendSuccessResponse("Delete Success",201);
        }else{
            return $this->sendFailResponse("Delete Fail",500);
        }
    }  

    Refresh

      public function refresh()
    {
        $old_token=JWTAuth::gettoken();    //获取过期token
        $new_token=JWTAuth::refresh($old_token);    //刷新token并返回
        JWTAuth::invalidate($old_token);    //销毁过期token
        return $this->response->array([
                'token'=>$new_token,
                'status_code'=>201
            ]);
    }  

    测试

  • Register
  • Login
  • RESTful-Get
  • RESTful-Post
  • RESTful-Put
  • RESTful-Delete
  • token refresh

Github

githhub地址

本文章首发在 Laravel China 社区