1、首先安装laravel(安装方式可以去官网或者laravel学院查看文档这里我写出安装5.4的命令)
通过composer安装指定版本
composer create-project --prefer-dist laravel/laravel blog "5.4*"
2、配置数据库
在目录结构下的.evn文件下配置
3.集成passport进项目
composer require laravel/passport
4.安装成功之后,我们需要设置他们的服务提供者,所以打开 config/app.php 文件,并在其中添加以下代码
注: laravel5.5
以上版本可以忽略这一步骤,此步骤争对 5.5
以下版本
5、注册之后,迁移数据表,Passport 会生成用于存储客户端和令牌的数据表
php artisan migrate
php artisan passport:install
6.打开 模型 app/User.php
我们需要增加 HasApiTokens
7
.打开 app/Providers/AuthServiceProvider.php
中增加 Passport::routers()
8.在 config/auth.php
中,更改 api
认证方式为 passport
9.、配置 routes/api.php 增加相应路由令牌
10.新建控制器(PassportController)截屏只能分2屏觉得麻烦 所以直接上代码
<?php
/**
* Time: 14:52
*/
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
class PassportController extends Controller
{
public $successStatus = 200;
/**
* login api
*
* @return \Illuminate\Http\Response
*/
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
/**
* Register api
*
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$input['password'] = bcrypt($input['password']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
return response()->json(['success'=>$success], $this->successStatus);
}
/**
* details api
*
* @return \Illuminate\Http\Response
*/
public function getDetails()
{
$user = Auth::user();
return response()->json(['success' => $user], $this->successStatus);
}
11.postman验证测试