返回首页 | www.long388.com

合作共赢、快速高效、优质的网站建设提供商

更多精品源码-尽在织梦模板-www.moke8.com

[编码]laravel 5.4 + dingo api + jwt 代替Passport

时间:2017-08-02 编辑:admin

$api- post('login', 'App\Http\Controllers\Api\Auth\LoginController@login'); $api- post('register', 'App\Http\Controllers\Api\Auth\RegisterController@register');

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

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

php artisan make:model User -m 

此命令可以添加迁移文件同时添加Model
迁移文件一般在database/migrations/时间格式_create_users_table.php
打开迁移文件修改以下内容:

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创建users表

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

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
 use Notifiable;
 * 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
添加如下内容:

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

打开Postman进行测试地址:

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

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){
 $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);
 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进行测试地址:

可以看到我们得到了token

拉取用户信息

在routers/api.php添加

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

终端运行:

php artisan make:controller App\\Http\\Controllers\\Api\\UsersController

在UsersController.php中添加

namespace App\Http\Controllers\Api;
use Dingo\Api\Routing\Helpers;
use Illuminate\Routing\Controller;
class UsersController extends Controller
 use Helpers;
 public function __construct()
 $this- middleware('api.auth');
 public function index(){
// return User::all();
 $user = $this- auth- user();
 return $user;

打开Postman进行测试地址:
注意因为我们设定了需要token才能拉取数据,所以在请求头Header中
我们添加了:Authorization :Bearer + token
Bearer是一种token_type在源码中有提到,应该是一种标准

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


浏览:

网站建设

流程

    网站建设流程