Laravel 开发API接口服务

原创 tiangr  2017-04-10 00:52  阅读 170 次

http://icodeit.org/2016/05/about-session-and-security-api-1/

http://icodeit.org/2016/05/about-session-and-security-api-2/

https://github.com/dingo/api

http://blog.rainy.im/2015/06/10/react-jwt-pretty-good-practice/

引入Dingo API 和 JWT

Laravel 安装方法

https://github.com/dingo/api/wiki/Installation
https://github.com/tymondesigns/jwt-auth/wiki/Installation

安装好之后,添加dingo API的配置到.env文件中:

API_STANDARDS_TREE=vnd
API_PREFIX=api
API_VERSION=v1
API_DEBUG=true

加入JWT 到dingo API的配置文件/config/api.php的auth数组中,连接两者:

'jwt' => function($app) {
    return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
}

打开文件 /app/Http/Kernel.php,按如下修改
protected $routeMiddleware = [
//        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,

GetUserFromToken

This will check the header and query string (as explained above) for the presence of a token, and attempts to decode it. The same events are fired, as above.

RefreshToken
This middleware will again try to parse the token from the request, and in turn will refresh the token (thus invalidating the old one) and return it as part of the next response. This essentially yields a single use token flow, which reduces the window of attack if a token is compromised, since it is only valid for the single request.

添加API路由

实例:

$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
    $api->group(['middleware' => 'api', 'namespace' => 'App\Http\Controllers\Api'], function ($api) {
        // Endpoints registered here will have the "api" middleware applied.
        $api->get('/rate', 'CongController@getRate');
    });
});

使用artisan查看注册路由:
php artisan api:routes

+------+----------+-----------+------+-------------------------------------------------+
| Host | Method | URI | Name | Action | Protected | Version(s) | Scope(s) | Rate Limit |
+------+----------+-----------+------+-------------------------------------------------+
| | GET|HEAD | /api/rate | | App\Http\Controllers\Api\CongController@getRate | No | v1 |
+------+----------+-----------+------+-------------------------------------------------+

在Controller基类中引入Helpers Traits
<?php

namespace App\Http\Controllers;

use Dingo\Api\Routing\Helpers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests, Helpers;
}
特别提示:本站资源全部免费下载,因服务器需经费维护,文中部分外链点击后会进入广告,请耐心等待5秒即可跳过广告进入目标页面。如遇页面外链打不开或下载地址失效,您可以在评论中指出错误,或扫描页面底部二维码。
本文地址:http://www.tiangr.com/bao-hu-ni-de-api.html
版权声明:本文为原创文章,版权归 tiangr 所有,欢迎分享本文,转载请保留出处!

发表评论


表情