摘要:前言由于在度娘找了半天根本一大堆版本,弄得我死去活來(lái)的,每個(gè)都試了一堆問(wèn)題,到底你們做完有沒(méi)有總結(jié)過(guò)一次然后有幾個(gè)使用,完全不行啊,太監(jiān)版不是我想要的。后來(lái),終于找到例子并實(shí)測(cè)成功。
前言
由于在度娘找了半天根本一大堆Copy版本,弄得我死去活來(lái)的,每個(gè)都試了一堆問(wèn)題,到底你們做完有沒(méi)有總結(jié)過(guò)一次?然后有幾個(gè)使用lunmen+dingo api+jwt,完全不行啊,太監(jiān)版不是我想要的。
后來(lái)Google,終于找到例子并實(shí)測(cè)成功。直接來(lái)了
composer create-project --prefer-dist laravel/laravel myApiProject安裝dingo api
在composer.json中添加
composer require dingo/api:1.0.x@dev
在config/app.php
"providers" => [ //前面很多 DingoApiProviderLaravelServiceProvider::class, ]
發(fā)布配置文件
終端運(yùn)行
php artisan vendor:publish --provider="DingoApiProviderLaravelServiceProvider"
打開(kāi).env文件,把dingo的配置放到最后面
API_STANDARDS_TREE=vnd // 環(huán)境 API_SUBTYPE=myapp // 子類型 API_PREFIX=api // 前綴 API_DOMAIN=api.myapp.com //子域名 (前綴和子域名只能存在一個(gè))可選 API_VERSION=v1 // 版本 API_NAME=My API // 名字(使用API Blueprint命令才會(huì)用到) API_CONDITIONAL_REQUEST=false // 帶條件的請(qǐng)求 API_STRICT=false // Strict模式 API_DEFAULT_FORMAT=json // 響應(yīng)格式 API_DEBUG=true // 調(diào)試模式
下面是我的配置:
API_STANDARDS_TREE=vnd API_SUBTYPE=emall API_PREFIX=api API_VERSION=v1
沒(méi)必要每個(gè)都配上去,主要的配一下就可以了
安裝jwt還是composer.json
"require-dev": { "tymon/jwt-auth": "1.0.*" }, "minimum-stability": "dev", "prefer-stable": true
其實(shí)只需要加上,下面是我的寫法,上面是國(guó)外的寫法
"tymon/jwt-auth": "1.0.*@dev"
運(yùn)行composer update將dingo和jwt裝上去
添加jwt的認(rèn)證
在config/api.php添加內(nèi)容
"auth" => [ "jwt" => DingoApiAuthProviderJWT::class ]
在config/app.php
"providers" => [ // 前面很多 TymonJWTAuthProvidersLaravelServiceProvider::class ], "aliases" => [ // 前面很多 "JWTAuth" => TymonJWTAuthFacadesJWTAuth::class ]
在終端運(yùn)行:
php artisan vendor:publish --provider="TymonJWTAuthProvidersLaravelServiceProvider"
會(huì)生成config/jwt.php 這是jwt的配置文件
生成jwt的key到.env文件運(yùn)行:
php artisan jwt:secret路由
在routers/api.php
中新建內(nèi)容,兩個(gè)路徑分別是注冊(cè)和登錄:
//這句接管路由 $api = app("DingoApiRoutingRouter"); $api->version("v1", function ($api) { $api->post("login", "AppHttpControllersApiAuthLoginController@login"); $api->post("register", "AppHttpControllersApiAuthRegisterController@register"); });
生成兩個(gè)controller
終端輸入:
php artisan make:controller AppHttpApiAuthLoginController php artisan make:controller AppHttpApiAuthRegisterController數(shù)據(jù)庫(kù)
備置.env文件
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=databasename DB_USERNAME=root DB_PASSWORD=
添加遷移文件,當(dāng)然你也可以使用php artisan make:auth 安裝LV自帶的用戶
下面我們用新建的吧
終端運(yùn)行:
php artisan make:model User -m
此命令可以添加遷移文件同時(shí)添加Model
遷移文件一般在database/migrations/時(shí)間格式_create_users_table.php
打開(kāi)遷移文件修改以下內(nèi)容:
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(); }); }
終端運(yùn)行:php artisan migrate創(chuàng)建users表
打開(kāi)我們新建的Model在App/下User.php
添加如下內(nèi)容:
use IlluminateNotificationsNotifiable; use IlluminateFoundationAuthUser as Authenticatable; use TymonJWTAuthContractsJWTSubject; 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 []; } }注冊(cè)
在之前建的App/Http/Controller/Api/Auth/RegisterController.php
添加如下內(nèi)容:
use AppHttpControllersController; use AppUser; use DingoApiExceptionStoreResourceFailedException; use DingoApiRoutingHelpers; use IlluminateFoundationAuthRegistersUsers; use IlluminateHttpRequest; use IlluminateSupportFacadesValidator; use TymonJWTAuthFacadesJWTAuth; 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"]), ]); } }
打開(kāi)Postman進(jìn)行測(cè)試地址:http://127.0.0.1/myApiProject...
登錄在之前建的App/Http/Controller/Api/Auth/LoginController.php
use AppUser; use DingoApiRoutingHelpers; use IlluminateFoundationAuthAuthenticatesUsers; use IlluminateHttpRequest; use AppHttpControllersController; use IlluminateSupportFacadesHash; use SymfonyComponentHttpKernelExceptionUnauthorizedHttpException; use TymonJWTAuthFacadesJWTAuth; 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(); } }
打開(kāi)Postman進(jìn)行測(cè)試地址:http://127.0.0.1/myApiProject...
可以看到我們得到了token
拉取用戶信息在routers/api.php添加
$api->group(["middleware" => "api.auth"], function ($api) { $api->get("user", "AppHttpControllersApiUsersController@index"); });
終端運(yùn)行:
php artisan make:controller AppHttpControllersApiUsersController
在UsersController.php中添加
namespace AppHttpControllersApi; use DingoApiRoutingHelpers; use IlluminateRoutingController; 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; } }
打開(kāi)Postman進(jìn)行測(cè)試地址:http://127.0.0.1/myApiProject...
注意因?yàn)槲覀冊(cè)O(shè)定了需要token才能拉取數(shù)據(jù),所以在請(qǐng)求頭Header中
我們添加了:Authorization :Bearer + token
Bearer是一種token_type在源碼中有提到,應(yīng)該是一種標(biāo)準(zhǔn)
這里只提到了注冊(cè)登錄,但沒(méi)有管理Token,后面有時(shí)間再寫,已經(jīng)用了很多上班時(shí)間。。。
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/31969.html
showImg(https://segmentfault.com/img/bV6aHV?w=1280&h=800); 社區(qū)優(yōu)秀文章 Laravel 5.5+passport 放棄 dingo 開(kāi)發(fā) API 實(shí)戰(zhàn),讓 API 開(kāi)發(fā)更省心 - 自造車輪。 API 文檔神器 Swagger 介紹及在 PHP 項(xiàng)目中使用 - API 文檔撰寫方案 推薦 Laravel API 項(xiàng)目必須使用的 8 個(gè)...
摘要:最近在寫一個(gè)前后端分離項(xiàng)目,本來(lái)想用開(kāi)發(fā)的,但是略感笨重,于是想到了的和新出的。更改看守器驅(qū)動(dòng)將配置文件中授權(quán)看守器的的選項(xiàng)改為。然后在你的前端請(qǐng)求里需要加入一個(gè)參數(shù)然后在你需要使用到認(rèn)證的路由里使用中間件,一切就大功告成啦 最近在寫一個(gè)前后端分離項(xiàng)目,本來(lái)想用 Jwt-auth + Dingo 開(kāi)發(fā)的,但是略感笨重,于是想到了 Laravel 的 Passport 和 5.5 新出的...
摘要:我的博客中文文檔中使用輔助文章參考這篇文章基本就能搭建出環(huán)境,我使用的版本跟他一樣,不知道別的版本有啥大的區(qū)別,但是網(wǎng)上找的其他一些文章使用的是舊的版本,封裝的東西路徑可能不一樣,可能會(huì)保錯(cuò),有些文檔還說(shuō)要手動(dòng)添加和,其實(shí)新版本不需要。 我的github博客:https://zgxxx.github.io/ dingo api 中文文檔: https://www.bookstack....
摘要:看到社區(qū)常有人問(wèn)用于密碼驗(yàn)證方式來(lái)獲取的問(wèn)題,剛好我最近一個(gè)項(xiàng)目使用,也是使用的密碼授權(quán)來(lái)做驗(yàn)證,對(duì)于如何做登錄登出,以及多賬號(hào)系統(tǒng)的認(rèn)證等常用場(chǎng)景做一下簡(jiǎn)單的使用小總結(jié)。 看到Laravel-China社區(qū)常有人問(wèn)Laravel Passport用于密碼驗(yàn)證方式來(lái)獲取Token的問(wèn)題,剛好我最近一個(gè)API項(xiàng)目使用Laravel Dingo Api+Passport,也是使用Oauth...
摘要:之前我們已經(jīng)準(zhǔn)備好了基本的安裝過(guò)程現(xiàn)在我們?nèi)?shí)現(xiàn)一下具體的業(yè)務(wù)部分用戶的登錄與注冊(cè)對(duì)于用戶注冊(cè)這對(duì)于一款應(yīng)用來(lái)說(shuō)再正常不過(guò)了為了接下來(lái)我們的效果我們可以去生成一個(gè)即在項(xiàng)目終端執(zhí)行生成用戶之后我們暫時(shí)先不去編輯字段后面我們需要用到時(shí)再加返回字 之前我們已經(jīng)準(zhǔn)備好了基本的安裝過(guò)程 現(xiàn)在我們?nèi)?shí)現(xiàn)一下具體的業(yè)務(wù)部分 用戶的登錄與注冊(cè) 對(duì)于用戶注冊(cè) 這對(duì)于一款應(yīng)用來(lái)說(shuō)再正常不過(guò)了 為了接下來(lái)...
閱讀 982·2023-04-26 03:03
閱讀 2289·2021-10-12 10:12
閱讀 1285·2021-09-24 09:48
閱讀 1738·2021-09-22 15:25
閱讀 3420·2021-09-22 15:15
閱讀 1010·2019-08-29 16:21
閱讀 1129·2019-08-28 18:00
閱讀 3496·2019-08-26 13:44