Laravel 5.4+ Dingo +Jwt 快速搭建 API系统
2021-04-13 14:28
标签:composer dingo jwt laravel5.5 api 搭建过程记录 : 我们采用 laravel 5.4 ,因为5.6好像比这更简洁,等我使用过后再来分享 __ 执行安装 配置项目 config/api.php 发布配置文件 : 终端执行 生成 jwt key 写入.env 在 .env 中,把 dingo 配置在最后 上面的配置不是都是必要的,可根据实际情况进行选择(上面配置时参考网络配置),如: __ 路由: 生成 Controller __ 如果不适用laravel 自带的认证系统,可以使用数据迁移 修改内容 生成表 编辑 Model/Users.php __ __ __ 编辑 UsersController.php 每次请求需要加 Header Laravel 5.4+ Dingo +Jwt 快速搭建 API系统 标签:composer dingo jwt laravel5.5 api 原文地址:http://blog.51cto.com/12750968/2109459 刚进入新公司,比较忙,只能抽时间来写写比较简短的博文总结,还望见谅。
最近公司要从实业转型线上,决定用laravel 来做快速开发,而一些同事之前没有用过laravel,尤其是api 的快速搭建,一致想让我把搭建过程给分享出来,此为背景----也算是治疗懒癌的动机 ^_^ ~~~
__
创建 laravel 项目composer create-project --prefer-dist laravle/laravel myProject ‘5.4.*‘
安装 Dingo + jwt"require":{
"dingo/api": "1.0.0-beta8",
"tymon/jwt-auth": "1.0.0-beta.3"
},
"minimum-stability":"dev",
composer update
config/app.php"providers"=>[
...
Dingo\Api\Provider\LaravelServiceProvider::class,
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],
‘aliases‘ => [
...
‘JWTAuth‘ => Tymon\JWTAuth\Facades\JWTAuth::class
]
‘auth‘ => [
‘jwt‘ => Dingo\Api\Auth\Provider\JWT::class
]
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider" //生成 api.php
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" //生成 jwt.php
php artisan jwt:secret
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
在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‘);
});
php artisan make:controller Api/Auth/LoginController
php artisan make:controller Api/Auth/RegisterController
数据库配置 .envDB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=51tbk.com
DB_USERNAME=root
DB_PASSWORD=123
php artisan make:model User -m //生成user 模型的同时,创建数据迁移
单独生成迁移文件
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
getKey();
}
public function getJWTCustomClaims(){
return [];
}
}
注册 RegisterController.phpvalidator($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" => "注册成功",
"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‘]),
]);
}
}
登录 LoginController.phpemail)->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();
}
}
获取用户信息
routes/api.php$api->group([‘middleware‘ => ‘api.auth‘], function ($api) {
$api->get(‘user‘, ‘App\Http\Controllers\Api\UsersController@index‘);
});
php artisan make:controller Api/UsersController
Authorization :Bearer + token
文章标题:Laravel 5.4+ Dingo +Jwt 快速搭建 API系统
文章链接:http://soscw.com/index.php/essay/75236.html