搭建前提:laravel5.5已安装完成,需要安装laravel5.5的请查看我的博客,有一篇安装laravel5.5的文章
1、在创建好的项目中,找到composer.json文件修改如下图
"dingo/api": "1.0.0-beta8"
"minimum-stability":"dev",
2、执行如下命令(此处需要token,看步骤3)
composer update
3、进入 https://github.com/settings/tokens 点击 「Generate new token」 新建一个 Token,选择默认新建就行,然后就会得到一个 Token,然后输入这个值就 OK 了(内容随便填),复制好了token,在命令行右键即可(右键已经粘贴了,看不见,直接回车即可),下面是我的token,可以试下能否使用
7e98ece06b05c43c720ba691f9377216ce5d0c19
4、安装jwt
composer require tymon/jwt-auth:dev-develop --prefer-source
5、配置项目config/app.php
Dingo\Api\Provider\LaravelServiceProvider::class,
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
6、发布配置文件
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider" //生成 api.php
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" //生成 jwt.php
7、生成 JWT_SECRET 写入.env
php artisan jwt:secret
8、配置config/api.php
'jwt' => Dingo\Api\Auth\Provider\JWT::class
9、在 .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 // 调试模式
ps:直接复制放入会报错(下面代码才对)
API_STANDARDS_TREE=vnd
API_SUBTYPE=myapp
API_PREFIX=api
API_DOMAIN=api.myapp.com
API_VERSION=v1
API_NAME='My API'
API_CONDITIONAL_REQUEST=false
API_STRICT=false
API_DEFAULT_FORMAT=json
API_DEBUG=true
10、在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');
});
生成LoginController和RegisterController
php artisan make:controller Api/Auth/LoginController
php artisan make:controller Api/Auth/RegisterController
11、数据库配置 .env(配置好要新建对应的数据库)
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel5
DB_USERNAME=root
DB_PASSWORD=root
12、使用User模型创建对应的数据表
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
13、到这里呢,其实整个api系统已经搭建完毕了,接下来就是如何进行测试了,好,那就开始吧!
1)新建auth控制器
<?php
/**
* Date: 17/10/12
* Time: 01:07
*/
namespace App\Http\Api\V1\Controllers;
use Dingo\Api\Routing\Helpers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use App\User;
class AuthController extends BaseController
{
use Helpers;
protected $guard = 'api';//设置使用guard为api选项验证,请查看config/auth.php的guards设置项,重要!
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login','register']]);
}
public function test(){
echo "test!!";
}
public function register(Request $request)
{
$rules = [
'name' => ['required'],
'email' => ['required'],
'password' => ['required', 'min:6', 'max:16'],
];
$payload = $request->only('name', 'email', 'password');
$validator = Validator::make($payload, $rules);
// 验证格式
if ($validator->fails()) {
return $this->response->array(['error' => $validator->errors()]);
}
// 创建用户
$result = User::create([
'name' => $payload['name'],
'email' => $payload['email'],
'password' => bcrypt($payload['password']),
]);
if ($result) {
return $this->response->array(['success' => '创建用户成功']);
} else {
return $this->response->array(['error' => '创建用户失败']);
}
}
/**
* Get a JWT token via given credentials.
*
* @param \Illuminate\Http\Request $request
*
* @return \Illuminate\Http\JsonResponse
*/
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
//$token = $this->guard('api')->tokenById($user->id);
//$token = $this->guard('api')->attempt($user);
if ($token = $this->guard()->attempt($credentials)) {
return $this->respondWithToken($token);
}
return $this->response->errorUnauthorized('登录失败');
}
/**
* Get the authenticated User
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
//return response()->json($this->guard()->user());
return $this->response->array($this->guard()->user());
}
/**
* Log the user out (Invalidate the token)
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
$this->guard()->logout();
//return response()->json(['message' => 'Successfully logged out']);
return $this->response->array(['message' => '退出成功']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken($this->guard()->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => $this->guard()->factory()->getTTL() * 60
]);
}
/**
* Get the guard to be used during authentication.
*
* @return \Illuminate\Contracts\Auth\Guard
*/
public function guard()
{
return Auth::guard($this->guard);
}
}
2)编写路由规则
3)使用postman测试注册,注意我的路由,api前缀是因为.env文件配置的,这个必须配置,相关的其他参数解释自己看文档,在这里我只配置了访问的前缀,我只演示注册,其他的方法自己可以亲自测试,有些参数会唯一,所以测试的时候注意数据库是否已存在,好了,本教程到这里结束了,有问题留言,我会很快回复的