lumen集成jwt dinggo

链接:http://laravelacademy.org/post/3640.html

一。 Composer安装jwt扩展包:
composer 添加 tymon/jwt-auth: “1.0.0-rc.1”

composer require tymon/jwt-auth:1.0.0-rc.1

二。在bootstrap中的app.php中添加
1。注册

$app->register(App\Providers\AuthServiceProvider::class);

2。然后注册需要用到的对应门面:
首先需要打开注释:
$app->withFacades();

class_alias('Tymon\JWTAuth\Facades\JWTAuth', 'JWTAuth');
class_alias('Tymon\JWTAuth\Facades\JWTFactory', 'JWTFactory');

3。然后发布相应配置文件:

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"

4。最后生成密钥:

php artisan jwt:generate

如果你想要将其添加到.env文件中,在.env中创建JWT_SECRET字段并再次执行生成密钥的命令。
5。在config—auth.php中进行配置

'guards' => [
        'api' => [
            'driver' => 'jwt',
            'provider' => 'user',
        ],
    ],
  'providers' => [
        'user' => [
            'driver' => 'eloquent',
            'model'  => \App\Models\User::class,
        ],
    ],

6。在app–model–User.php中进行设备

<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
    use Authenticatable, Authorizable;

    /**
     * 与模型关联的数据表。
     *
     * @var string
     */
    protected $table = 'user';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'ding_userid'
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
//        'password',
    ];

    use SoftDeletes;
    //...其他一些设置
    protected $dates = ['delete_at'];


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

    public function getJWTCustomClaims()
    {
        return [];
    }

    //批量更新
    public function updateBatch($multipleData = [])
    {
        try {
            if (empty($multipleData)) {
                throw new \Exception("数据不能为空");
            }
            //$tableName = DB::getTablePrefix() . $this->getTable(); // 表名
            $tableName = $this->table; // 表名
            $firstRow = current($multipleData);
            $updateColumn = array_keys($firstRow);
            // 默认以ding_userid为条件更新,如果没有ID则以第一个字段为条件
            $referenceColumn = isset($firstRow['ding_userid']) ? 'ding_userid' : current($updateColumn);
            unset($updateColumn[0]);
            unset($updateColumn[9]);
            // 拼接sql语句
            $updateSql = "UPDATE " . $tableName . " SET ";
            $sets = [];
            $bindings = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings = array_merge($bindings, $whereIn);
            $whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            // 传入预处理sql语句和对应绑定数据
            return DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
            return false;
        }
    }
}

lumen设置中间件
1。在bootstrap-app中设置中间件

$app->middleware([
    App\Http\Middleware\CorsMiddleware::class
//    App\Http\Middleware\ExampleMiddleware::class
]);

$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);

2。在app–middleware中添加两个文件
CorsMiddleware.php和Authenticate.php

Authenticate.php【解决没登录的问题】
当遇到复杂请求时,浏览器为了防止跨域请求无端对服务器数据造成损坏会先发送一个 Options 的预检请求。服务器应该对其进行处理,决定是否允许当前客户端进一步发起跨域请求。随后浏览器会根据 Options 请求的响应信息来决定是否进行下一步真实的请求。

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;

class Authenticate
{
    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if ($this->auth->guard($guard)->guest()) {
            // 修改非授权条件下的返回格式 确保所有api接口返回格式统一
            return response(array(
                'message' => 'Unauthorized.',
                'status_code' => 401
            ), 401);
        }

        return $next($request);
    }
}

CorsMiddleware.php【解决跨域的问题】

简而言之
OPTIONS请求方法的主要用途有两个:
1、获取服务器支持的HTTP请求方法;也是黑客经常使用的方法。
2、用来检查服务器的性能。例如:AJAX进行跨域请求时的预检,需要向另外一个域名的资源发送一个HTTP OPTIONS请求头,用以判断实际发送的请求是否安全。

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin' => getenv('ACCESS_CONTROL_ALLOW_ORIGIN'),
            'Access-Control-Allow-Methods' => getenv('ACCESS_CONTROL_ALLOW_METHODS'),
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age' => '86400',
            'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
        ];
 // 跨域请求时浏览器会先使用 options 方法判断是否允许当前域名发送跨域请求
        if ($request->isMethod('OPTIONS')) {
            return response()->json('{"method":"OPTIONS"}', 200, $headers);
        }
     // 加入允许跨域响应头并直接发送响应信息
     // OPTIONS方法用来查询针对请求URI指定资源支持的方法(客户端询问服务器可以提交哪些请求方法)
        $response = $next($request);
        foreach ($headers as $key => $value) {
            $response->header($key, $value);
        }

        return $response;
    }
}

lumen集成dinggo-api

1。Composer安装dinggo:

composer require dingo/api:2.0.0-alpha1

2。在config/app.php中注册服务提供者到providers数组

// dingo/api
$app->register(Dingo\Api\Provider\LumenServiceProvider::class);
// dingo config for jwt
app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
    return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
});

3。在.env中进行配置

API_STANDARDS_TREE=vnd
API_SUBTYPE=crm  //Subtype 子类型
API_PREFIX=api   //Prefixes and Subdomains 前缀和子域名
API_VERSION=v1   //Version 版本
API_DEBUG=true   //开启Debug Mode 调试模式

4。在config/app.php中添加配置
Authentication Providers

// dingo config for jwt
app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
    return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
});

5。现在就可以在routes.php中写路由了


$api = app('Dingo\Api\Routing\Router');
$api->version('v1', [
    'namespace' => 'App\Http\Controllers\Api',
], function ($api) {
    $api->get('config', [
        'as' => 'auth.config',
        'uses' => 'AuthController@jsConfig'
    ]);
    })

6。要利用响应生成器, 你的控制器需要使用 Dingo\Api\Routing\Helpers trait。为了在你的控制器里保持引入和使用这个 trait,你可以创建一个基础控制器,然后你的所有的 API 控制器都继承它。

use Dingo\Api\Routing\Helpers;
use Illuminate\Routing\Controller;

class BaseController extends Controller
{
    use Helpers;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值