因爲在度娘找了半天根本一大堆Copy版本,弄得我死去活來的,每一個都試了一堆問題,到底大家作完有沒有總結過一次?而後有幾個使用lunmen+dingo api+jwt,徹底不行啊,太監版不是我想要的。
後來Google,終於找到例子並實測成功。直接來了php
composer create-project --prefer-dist laravel/laravel myApiProject
在composer.json中添加mysql
composer require dingo/api:1.0.x@dev
在config/app.php
laravel
'providers' => [ //前面不少 Dingo\Api\Provider\LaravelServiceProvider::class, ]
發佈配置文件
終端運行sql
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
打開.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 // 調試模式
下面是個人配置:json
API_STANDARDS_TREE=vnd API_SUBTYPE=emall API_PREFIX=api API_VERSION=v1
不必每一個都配上去,主要的配一下就能夠了api
仍是composer.json
app
"require-dev": { "tymon/jwt-auth": "1.0.*" }, "minimum-stability": "dev", "prefer-stable": true
其實只須要加上,下面是個人寫法,上面是國外的寫法composer
"tymon/jwt-auth": "1.0.*@dev"
運行composer update
將dingo和jwt裝上去ide
添加jwt的認證
在config/api.php
添加內容
'auth' => [ 'jwt' => Dingo\Api\Auth\Provider\JWT::class ]
在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"
會生成config/jwt.php
這是jwt
的配置文件
生成jwt
的key
到.env
文件運行:
php artisan jwt:secret
在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'); });
生成兩個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->save()){ $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
進行測試地址:http://127.0.0.1/myApiProject...
在以前建的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
進行測試地址:http://127.0.0.1/myApiProject...
能夠看到咱們獲得了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
進行測試地址:http://127.0.0.1/myApiProject...
注意由於咱們設定了須要token
才能拉取數據,因此在請求頭Header
中
咱們添加了:Authorization :Bearer + token
Bearer
是一種token_type
在源碼中有提到,應該是一種標準
這裏只提到了註冊登陸,但沒有管理Token,後面有時間再寫,已經用了不少上班時間。。。