溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Laravel 5.5+ Dingo +Jwt 快速搭建 API系統(tǒng)

發(fā)布時(shí)間:2020-05-23 16:48:57 來(lái)源:網(wǎng)絡(luò) 閱讀:34510 作者:指尖芳華 欄目:web開(kāi)發(fā)
    剛進(jìn)入新公司,比較忙,只能抽時(shí)間來(lái)寫(xiě)寫(xiě)比較簡(jiǎn)短的博文總結(jié),還望見(jiàn)諒。
    最近公司要從實(shí)業(yè)轉(zhuǎn)型線(xiàn)上,決定用laravel 來(lái)做快速開(kāi)發(fā),而一些同事之前沒(méi)有用過(guò)laravel,尤其是api 的快速搭建,一致想讓我把搭建過(guò)程給分享出來(lái),此為背景

搭建過(guò)程記錄 laravel 5.5
__
創(chuàng)建 laravel 項(xiàng)目

composer create-project --prefer-dist laravle/laravel myProject  '5.5.*'

__
安裝 Dingo

"require":{
        "dingo/api": "1.0.0-beta8"
},
"minimum-stability":"dev",

執(zhí)行安裝

composer update

安裝jwt

composer require tymon/jwt-auth:dev-develop --prefer-source

配置項(xiàng)目
config/app.php

"providers"=>[
        ...
        Dingo\Api\Provider\LaravelServiceProvider::class,
        Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],

'aliases' => [
    ...
    'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
        'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class
]

發(fā)布配置文件 : 終端執(zhí)行

php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"  //生成 api.php
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"  //生成 jwt.php

或者
php artisan vendoer:publish 
選擇編號(hào)即可發(fā)布

生成 JWT_SECRET 寫(xiě)入.env

php artisan jwt:secret  

config/api.php

'auth' => [
    'jwt' => Dingo\Api\Auth\Provider\JWT::class
]

在 .env 中,把 dingo 配置在最后

API_STANDARDS_TREE=vnd // 環(huán)境
API_SUBTYPE=myapp // 子類(lèi)型
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)試模式

上面的配置不是都是必要的,可根據(jù)實(shí)際情況進(jìn)行選擇(上面配置時(shí)參考網(wǎng)絡(luò)配置),如:

API_STANDARDS_TREE=vnd
API_SUBTYPE=emall
API_PREFIX=api
API_VERSION=v1

__

路由:
在routers/api.php中新建內(nèi)容,兩個(gè)路徑分別是注冊(cè)和登錄:

//接管路由
$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 Api/Auth/LoginController
php artisan make:controller Api/Auth/RegisterController  

__
數(shù)據(jù)庫(kù)配置 .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=51tbk.com
DB_USERNAME=root
DB_PASSWORD=123

如果不適用laravel 自帶的認(rèn)證系統(tǒng)(php artisan make:auth)會(huì)創(chuàng)建模板,可以使用數(shù)據(jù)遷移

php artisan make:model User -m   //生成user 模型的同時(shí),創(chuàng)建數(shù)據(jù)遷移
單獨(dú)生成遷移文件
php artisan make:migration create_users_table

修改內(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();
    });
}

生成表

php artisan migrate

編輯 Model/Users.php

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Users extends Authenticatable implements JWTSubject 
{
    use Notifiable;

    protected $fillable = ['name','email','password'];

    protected $hidden = ['password','remember_token'];

    public function getJWTIdentifier(){
        return $this->getKey();
    }

    public function getJWTCustomClaims(){
        return [];
    }
}

__
注冊(cè) RegisterController.php

<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use App\User;
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" => "注冊(cè)成功",
                "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.php

<?php

use App\Http\Controllers\Controller;
use App\User;
use Dingo\Api\Routing\Helpers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
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();
    }
}

__
獲取用戶(hù)信息
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

編輯 UsersController.php

每次請(qǐng)求需要加 Header

Authorization :Bearer + token
向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI