Kong Gateway - 01 基于网关服务的基本验证(Basic Authentication)

范例项目bookstrore结构截图

1). Host IP : 192.168.10.10/24

[root@contoso ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:b9:f7:76 brd ff:ff:ff:ff:ff:ff
    inet 192.168.10.10/24 brd 192.168.10.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:feb9:f776/64 scope link 
       valid_lft forever preferred_lft forever
3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN qlen 1000
    link/ether 52:54:00:7d:d4:dd brd ff:ff:ff:ff:ff:ff
    inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
       valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast master virbr0 state DOWN qlen 1000
    link/ether 52:54:00:7d:d4:dd brd ff:ff:ff:ff:ff:ff

2). 自定义域名contoso.com,并且建立IP与域名之间的映射关系

[root@contoso ~]# cat > /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.10.10   contoso.com

3). 使用ThinkPHP 5.1 创建bookstrore项目

[myth@contoso ~]$ cd /home/myth/www && composer create-project topthink/think bookstore --prefer-dist

4). 修改Apache服务器运行的默认用户以及默认用户组

[myth@contoso ~]$ whoami   # myth是我登录Linux系统的用户名,登录密码是123
myth

[myth@contoso ~]$  su -    # 提升终端命令的运行环境到root管理员模式下
password: 123
[root@contoso ~]# sed -i -- 's/^User apache/User myth/g' /etc/httpd/conf/httpd.conf
[root@contoso ~]# sed -i -- 's/^Group apache/Group myth/g' /etc/httpd/conf/httpd.conf

[root@contoso ~]# cat -n /etc/httpd/conf/httpd.conf  
66  User myth
67  Group myth

5). 配置虚拟主机

[root@contoso ~]# cat > /etc/httpd/conf.d/httpd-vhosts.conf
<Directory "/home/myth/www/bookstore">
        Options +Indexes +FollowSymLinks
        Order allow,deny
        Allow from all
        AllowOverride All
        Require all granted
</Directory>
<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "/home/myth/www/bookstore/public"
    ServerName contoso.com
    ServerAlias contoso.com
    ErrorLog "/home/myth/log/httpd/contoso-com-error_log"
    CustomLog "/home/myth/log/httpd/contoso-com-access_log" common
</VirtualHost>

6). 创建books书籍数据表基于Restful API风格的数据操作(增删改查)接口

    a). 数据库初始化
    CREATE DATABASE bookstrore;
    CREATE TABLE `books` (
      `id` bigint(20) NOT NULL AUTO_INCREMENT,
      `title` varchar(80) DEFAULT NULL,
      `author` text DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    insert into `books` (`id`, `title`, `author`) values('1','Fashion That Changed the World','Jennifer Croll');
    insert into `books` (`id`, `title`, `author`) values('2','Brigitte Bardot - My Life in Fashion','Henry-Jean Servat and Brigitte Bardot');
    insert into `books` (`id`, `title`, `author`) values('3','The Fashion Image','Thomas Werner');
    b). 创建控制器文件/home/myth/www/bookstore/application/api/controller/v1/Book.php
<?php
namespace app\api\controller\v1;
use think\Controller;
use think\Request;
use think\Db;
class Book extends Controller {
    public function getBooks() {
        $books = Db::table('books')->select();
        return json($books);
    }

    public function getBookById($id) {
        $book = Db::name('books')->where('id', $id)->select();
        return json($book);
    }

    public function addBook(Request $request) {
        $title = $request->param('title');
        $author = $request->param('author');
        $book = ['title' => $title, 'author' => $author];
        // 启动事务
        Db::startTrans();
        try {
            Db::name('books')->insert($book);
            // 提交事务
            Db::commit();
        } catch (Exception $ex) {
            // 回滚事务
            Db::rollback();
            return json(['message' => 'inserting not successfully']);
        }
        return json(['message' => 'inserted successfully']);
    }

    public function deleteBookById($id) {
        // 启动事务
        Db::startTrans();
        try {
            Db::name('books')->where('id', $id)->delete();
            // 提交事务
            Db::commit();
        } catch (Exception $ex) {
            // 回滚事务
            Db::rollback();
            return json(['message' => 'deleting not successfully']);
        }
        return json(['message' => 'deleted successfully']);
    }

    public function updateBookById(Request $request) {
        $id = $request->param('id');
        $title = $request->param('title');
        $author = $request->param('author');
        $book = ['title' => $title, 'author' => $author];
        // 启动事务
        Db::startTrans();
        try {
            Db::table('books')->where('id', $id)->update($book);
            // 提交事务
            Db::commit();
        } catch (Exception $ex) {
            // 回滚事务
            Db::rollback();
             return json(['message' => 'updating not successfully']);
        }
        return json(['message' => 'updated successfully']);
    }
}
创建控制器文件/home/myth/www/bookstore/application/api/controller/Info.php
<?php
namespace app\api\controller;
use think\Controller;

class Info extends Controller {

    public function index() {
        $list = [
            'books' => [
                'getBookById' => 'GET  http://contoso.com/v1/books/2',
                'addBook' => 'POST  http://contoso.com/v1/books',
                'deleteBookById' => 'DELETE  http://contoso.com/v1/books/2',
                'updateBookById' => 'PUT  http://contoso.com/v1/books',
                'getBooks' => 'GET  http://contoso.com/v1/books'
            ]
        ];
        return json($list);
    }

}    
c). 配置路由/home/myth/www/bookstore/route/route.php   
<?php

// GET    http://contoso.com/v1/books/2
Route::get(':version/books/:id', 'api/:version.Book/getBookById'); 
// POST   http://contoso.com/v1/books
Route::post(':version/books', 'api/:version.Book/addBook');  
// DELETE http://contoso.com/v1/books/2
Route::delete(':version/books/:id', 'api/:version.Book/deleteBookById'); 
// PUT    http://contoso.com/v1/books
Route::put(':version/books', 'api/:version.Book/updateBookById'); 
// GET    http://contoso.com/v1/books
Route::get(':version/books', 'api/:version.Book/getBooks');           
// GET    http://contoso.com/v1
Route::get(':version', 'api/Info/index');        
return [

];
d). 自定义异常处理handle类/home/myth/www/bookstore/application/api/exception/Http.php
<?php
namespace app\api\exception;
use think\Request;
use think\exception\Handle;
use think\exception\HttpException;

class Http extends Handle {

    public function render(\Exception $e) {
        $request = new Request();
        if ($e instanceof HttpException) {
            $statusCode = $e->getStatusCode();
        }
        if (!isset($statusCode)) {
            $statusCode = 500;
        }
        $result = [
            'code' => $statusCode,
            'method' => $request->method(),
            'message' => $e->getMessage(),
            'url' => $request->url(true),
            'time' => $_SERVER['REQUEST_TIME']
        ];
        return json($result, $statusCode);
    }

}

别忘记修改配置文件/home/myth/www/bookstore/config/app.php

'exception_handle'       => '\app\api\exception\Http',

7). 检测范例接口的正确性



准备工作已经完成,现在开始正式进入主题

Basic Authentication
https://getkong.org/plugins/basic-authentication

[root@contoso ~]# kong start
Kong started

用Kong配置一个books服务
在安装并启动Kong之后,使用Kong的管理API端口8001添加一个名称为books的服务

[root@contoso ~]# curl -i -X POST \
--url http://localhost:8001/services/ \
--data 'name=books' \
--data 'url=http://contoso.com/v1/books'
HTTP/1.1 201 Created
Date: Wed, 02 May 2018 03:37:48 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{
    "host": "contoso.com", 
    "created_at": 1525203468, 
    "connect_timeout": 60000, 
    "id": "86ae5aea-2281-42a2-bbeb-7da04fa00c93", 
    "protocol": "http", 
    "name": "books", 
    "read_timeout": 60000, 
    "port": 80, 
    "path": "/v1/books", 
    "updated_at": 1525203468, 
    "retries": 5, 
    "write_timeout": 60000
}
添加一个路由(仅支持GET请求,paths[]的值必须与books服务中的/v1/books一致)
使books服务暴露出来以供用户访问,books服务可以添加多个路由。
paths[]=/v1/books 匹配的路由地址以http://contoso.com/v1/books开头的任何地址
[root@contoso ~]# curl -i -X POST \
--url http://localhost:8001/services/books/routes \
--data 'hosts[]=contoso.com' \
--data 'paths[]=/v1/books' \
--data 'methods[]=GET'
HTTP/1.1 201 Created
Date: Wed, 02 May 2018 03:44:20 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{
    "created_at": 1525203860, 
    "strip_path": true, 
    "hosts": [
        "contoso.com"
    ], 
    "preserve_host": false, 
    "regex_priority": 0, 
    "updated_at": 1525203860, 
    "paths": [
        "/v1/books"
    ], 
    "service": {
        "id": "86ae5aea-2281-42a2-bbeb-7da04fa00c93"
    }, 
    "methods": [
        "GET"
    ], 
    "protocols": [
        "http", 
        "https"
    ], 
    "id": "1c0fb531-db84-445a-911d-c61798053c49"
}
添加一个路由(仅支持POST请求,paths[]的值必须与books服务中的/v1/books一致)
使books服务暴露出来以供用户访问,books服务可以添加多个路由。
paths[]=/v1/books 匹配的路由地址以http://contoso.com/v1/books开头的任何地址
[root@contoso ~]# curl -i -X POST \
--url http://localhost:8001/services/books/routes \
--data 'hosts[]=contoso.com' \
--data 'paths[]=/v1/books' \
--data 'methods[]=POST'
HTTP/1.1 201 Created
Date: Wed, 02 May 2018 03:47:21 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{
    "created_at": 1525204041, 
    "strip_path": true, 
    "hosts": [
        "contoso.com"
    ], 
    "preserve_host": false, 
    "regex_priority": 0, 
    "updated_at": 1525204041, 
    "paths": [
        "/v1/books"
    ], 
    "service": {
        "id": "86ae5aea-2281-42a2-bbeb-7da04fa00c93"
    }, 
    "methods": [
        "POST"
    ], 
    "protocols": [
        "http", 
        "https"
    ], 
    "id": "aa4e321d-95e7-46a0-9b6e-2f2d56c21537"
}
添加一个路由(仅支持PUT请求,paths[]的值必须与books服务中的/v1/books一致)
使books服务暴露出来以供用户访问,books服务可以添加多个路由。
paths[]=/v1/books 匹配的路由地址以http://contoso.com/v1/books开头的任何地址
[root@contoso ~]# curl -i -X POST \
--url http://localhost:8001/services/books/routes \
--data 'hosts[]=contoso.com' \
--data 'paths[]=/v1/books' \
--data 'methods[]=PUT'
HTTP/1.1 201 Created
Date: Wed, 02 May 2018 03:49:29 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{
    "created_at": 1525204169, 
    "strip_path": true, 
    "hosts": [
        "contoso.com"
    ], 
    "preserve_host": false, 
    "regex_priority": 0, 
    "updated_at": 1525204169, 
    "paths": [
        "/v1/books"
    ], 
    "service": {
        "id": "86ae5aea-2281-42a2-bbeb-7da04fa00c93"
    }, 
    "methods": [
        "PUT"
    ], 
    "protocols": [
        "http", 
        "https"
    ], 
    "id": "ee528443-3597-4092-bb69-4d087ad8d534"
}
添加一个路由(仅支持DELETE请求,paths[]的值必须与books服务中的/v1/books一致)
使books服务暴露出来以供用户访问,books服务可以添加多个路由。
paths[]=/v1/books 匹配的路由地址以http://contoso.com/v1/books开头的任何地址
[root@contoso ~]# curl -i -X POST \
--url http://localhost:8001/services/books/routes \
--data 'hosts[]=contoso.com' \
--data 'paths[]=/v1/books' \
--data 'methods[]=DELETE'
HTTP/1.1 201 Created
Date: Wed, 02 May 2018 03:51:36 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{
    "created_at": 1525204296, 
    "strip_path": true, 
    "hosts": [
        "contoso.com"
    ], 
    "preserve_host": false, 
    "regex_priority": 0, 
    "updated_at": 1525204296, 
    "paths": [
        "/v1/books"
    ], 
    "service": {
        "id": "86ae5aea-2281-42a2-bbeb-7da04fa00c93"
    }, 
    "methods": [
        "DELETE"
    ], 
    "protocols": [
        "http", 
        "https"
    ], 
    "id": "c7259bfb-843a-441e-a9a2-412ccbc98572"
}
通过Kong在8000端口暴露出来的服务地址获得所有的书籍
[root@contoso ~]# curl -i -X GET \
--url http://localhost:8000/v1/books \
--header 'Host: contoso.com'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 186
Connection: keep-alive
Date: Wed, 02 May 2018 04:00:10 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.1.13
X-Powered-By: PHP/7.1.13
X-Kong-Upstream-Latency: 37
X-Kong-Proxy-Latency: 45
Via: kong/0.13.1

[
    {
        "id": 1, 
        "title": "Fashion That Changed the World", 
        "author": "Jennifer Croll"
    }, 
    {
        "id": 3, 
        "title": "Mongo in Action", 
        "author": "Tomson"
    }, 
    {
        "id": 4, 
        "title": "Redis in Action", 
        "author": "Jack Chen"
    }
]
通过Kong在8000端口暴露出来的服务地址获得id=3的书籍
[root@contoso ~]# curl -i -X GET \
--url http://localhost:8000/v1/books/3 \
--header 'Host: contoso.com'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 54
Connection: keep-alive
Date: Wed, 02 May 2018 04:03:30 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.1.13
X-Powered-By: PHP/7.1.13
X-Kong-Upstream-Latency: 24
X-Kong-Proxy-Latency: 0
Via: kong/0.13.1

[
    {
        "id": 3, 
        "title": "Mongo in Action", 
        "author": "Tomson"
    }
]
通过Kong在8000端口暴露出来的服务地址新增一条书籍记录
[root@contoso ~]# curl -i -X POST \
--url http://localhost:8000/v1/books \
--data-urlencode 'title=Fashion China' \
--data-urlencode 'author=Joe Brown' \
--header 'Host: contoso.com'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 35
Connection: keep-alive
Date: Wed, 02 May 2018 06:10:18 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.1.13
X-Powered-By: PHP/7.1.13
X-Kong-Upstream-Latency: 31
X-Kong-Proxy-Latency: 26
Via: kong/0.13.1

{"message":"inserted successfully"}
通过Kong在8000端口暴露出来的服务地址修改一条书籍记录
[root@contoso ~]# curl -i -X PUT \
--url http://localhost:8000/v1/books \
--data-urlencode 'id=1' \
--data-urlencode 'title=TiDB in Action' \
--data-urlencode 'author=Joe Brown' \
--header 'Host: contoso.com'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 34
Connection: keep-alive
Date: Wed, 02 May 2018 06:11:11 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.1.13
X-Powered-By: PHP/7.1.13
X-Kong-Upstream-Latency: 27
X-Kong-Proxy-Latency: 25
Via: kong/0.13.1

{"message":"updated successfully"}
通过Kong在8000端口暴露出来的服务地址删除一条书籍记录
[root@contoso ~]# curl -i -X DELETE \
--url http://localhost:8000/v1/books/3 \
--header 'Host: contoso.com'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 34
Connection: keep-alive
Date: Wed, 02 May 2018 06:11:53 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.1.13
X-Powered-By: PHP/7.1.13
X-Kong-Upstream-Latency: 27
X-Kong-Proxy-Latency: 28
Via: kong/0.13.1

{"message":"deleted successfully"}

重新初始化数据库books表

[root@contoso ~]# mysql -h127.0.0.1 -uroot -p123456
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 42
Server version: 10.2.12-MariaDB-log MariaDB Server

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> use bookstore
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [bookstore]> SELECT * FROM books;
+----+-----------------+-----------+
| id | title           | author    |
+----+-----------------+-----------+
|  1 | TiDB in Action  | Joe Brown |
|  4 | Redis in Action | Jack Chen |
|  5 | Fashion China   | Joe Brown |
+----+-----------------+-----------+
3 rows in set (0.00 sec)

MariaDB [bookstore]> DELETE FROM books;
Query OK, 3 rows affected (0.01 sec)

MariaDB [bookstore]> insert into `books` (`id`, `title`, `author`) values('1','Fashion That Changed the World','Jennifer Croll');
Query OK, 1 row affected (0.00 sec)

MariaDB [bookstore]> insert into `books` (`id`, `title`, `author`) values('2','Brigitte Bardot - My Life in Fashion','Henry-Jean Servat and Brigitte Bardot');
Query OK, 1 row affected (0.00 sec)

MariaDB [bookstore]> insert into `books` (`id`, `title`, `author`) values('3','The Fashion Image','Thomas Werner');
Query OK, 1 row affected (0.00 sec)

MariaDB [bookstore]> SELECT * FROM books;
+----+--------------------------------------+---------------------------------------+
| id | title                                | author                                |
+----+--------------------------------------+---------------------------------------+
|  1 | Fashion That Changed the World       | Jennifer Croll                        |
|  2 | Brigitte Bardot - My Life in Fashion | Henry-Jean Servat and Brigitte Bardot |
|  3 | The Fashion Image                    | Thomas Werner                         |
+----+--------------------------------------+---------------------------------------+
3 rows in set (0.00 sec)

MariaDB [bookstore]> 
使用Kong的管理端口8001查询所有已经添加路由配置信息列表
返回每条信息中的id(也就是route_id)值,随后我们会用到这些id来配置基本验证
[root@contoso ~]# curl -i -X GET \
--url http://localhost:8001/services/books/routes
HTTP/1.1 200 OK
Date: Wed, 02 May 2018 06:59:31 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{
    "next": null, 
    "data": [
        {
            "created_at": 1525203860, 
            "strip_path": true, 
            "hosts": [
                "contoso.com"
            ], 
            "preserve_host": false, 
            "regex_priority": 0, 
            "updated_at": 1525203860, 
            "paths": [
                "/v1/books"
            ], 
            "service": {
                "id": "86ae5aea-2281-42a2-bbeb-7da04fa00c93"
            }, 
            "methods": [
                "GET"
            ], 
            "protocols": [
                "http", 
                "https"
            ], 
            "id": "1c0fb531-db84-445a-911d-c61798053c49"    // route_id = id
        }, 
        {
            "created_at": 1525204041, 
            "strip_path": true, 
            "hosts": [
                "contoso.com"
            ], 
            "preserve_host": false, 
            "regex_priority": 0, 
            "updated_at": 1525204041, 
            "paths": [
                "/v1/books"
            ], 
            "service": {
                "id": "86ae5aea-2281-42a2-bbeb-7da04fa00c93"
            }, 
            "methods": [
                "POST"
            ], 
            "protocols": [
                "http", 
                "https"
            ], 
            "id": "aa4e321d-95e7-46a0-9b6e-2f2d56c21537"    // route_id = id
        }, 
        {
            "created_at": 1525204296, 
            "strip_path": true, 
            "hosts": [
                "contoso.com"
            ], 
            "preserve_host": false, 
            "regex_priority": 0, 
            "updated_at": 1525204296, 
            "paths": [
                "/v1/books"
            ], 
            "service": {
                "id": "86ae5aea-2281-42a2-bbeb-7da04fa00c93"
            }, 
            "methods": [
                "DELETE"
            ], 
            "protocols": [
                "http", 
                "https"
            ], 
            "id": "c7259bfb-843a-441e-a9a2-412ccbc98572"    // route_id = id
        }, 
        {
            "created_at": 1525204169, 
            "strip_path": true, 
            "hosts": [
                "contoso.com"
            ], 
            "preserve_host": false, 
            "regex_priority": 0, 
            "updated_at": 1525204169, 
            "paths": [
                "/v1/books"
            ], 
            "service": {
                "id": "86ae5aea-2281-42a2-bbeb-7da04fa00c93"
            }, 
            "methods": [
                "PUT"
            ], 
            "protocols": [
                "http", 
                "https"
            ], 
            "id": "ee528443-3597-4092-bb69-4d087ad8d534"    // route_id = id
        }
    ]
}
为route_id="c7259bfb-843a-441e-a9a2-412ccbc98572"的这条路由(即删除书籍的路由),启用basic-auth基本验证插
[root@contoso ~]# curl -i -X POST \
--url http://localhost:8001/routes/c7259bfb-843a-441e-a9a2-412ccbc98572/plugins \
--data "name=basic-auth"  \
--data "config.hide_credentials=true"
HTTP/1.1 201 Created
Date: Wed, 02 May 2018 07:39:11 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{
    "created_at": 1525246752000, 
    "config": {
        "hide_credentials": true, 
        "anonymous": ""
    }, 
    "id": "57f4dadb-2b9d-467c-b758-4b5f79c9ffdd", 
    "enabled": true, 
    "route_id": "c7259bfb-843a-441e-a9a2-412ccbc98572", 
    "name": "basic-auth"
}
通过Kong在8000端口暴露出来的服务地址删除一条书籍记录,
实际上是通过Kong在转发我的请求
[root@contoso ~]# curl -i -X DELETE \
--url http://localhost:8000/v1/books/3 \
--header 'Host: contoso.com'
HTTP/1.1 401 Unauthorized
Date: Wed, 02 May 2018 07:47:14 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
WWW-Authenticate: Basic realm="kong"
Server: kong/0.13.1

{"message":"Unauthorized"}
创建1个username=cathy的消费者
[root@contoso ~]# curl -i -X POST \
--url http://localhost:8001/consumers \
--data "username=cathy"
HTTP/1.1 201 Created
Date: Wed, 02 May 2018 08:08:01 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{"created_at":1525248482000,"username":"cathy","id":"3bba7a46-83b5-4107-bb2c-bf8c9f1983d2"}
创建1个username=jack且custom_id=abc123的消费者
[root@contoso ~]# curl -i -X POST \
--url http://localhost:8001/consumers \
--data 'username=jack' \
--data "custom_id=abc123"
HTTP/1.1 201 Created
Date: Wed, 02 May 2018 08:09:19 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{"custom_id":"abc123","created_at":1525248559000,"username":"jack","id":"59fc9bc8-3149-4409-b3a2-e55216a79ac0"}
创建1个custom_id=456789的消费者
[root@contoso ~]# curl -i -X POST \
--url http://localhost:8001/consumers \
--data 'custom_id=456789'
HTTP/1.1 201 Created
Date: Wed, 02 May 2018 08:10:10 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{"custom_id":"456789","created_at":1525248611000,"id":"65a4e411-b295-47c2-809d-f0d425c72415"}
使用Kong的管理端口8001查询所有已经添加消费者信息列表
[root@contoso ~]# curl -i -X GET \
--url http://localhost:8001/consumers
{
    "total": 3, 
    "data": [
        {
            "created_at": 1525248482000, 
            "username": "cathy", 
            "id": "3bba7a46-83b5-4107-bb2c-bf8c9f1983d2"
        }, 
        {
            "custom_id": "456789", 
            "created_at": 1525248611000, 
            "id": "65a4e411-b295-47c2-809d-f0d425c72415"
        }, 
        {
            "custom_id": "abc123", 
            "created_at": 1525248559000, 
            "username": "jack", 
            "id": "59fc9bc8-3149-4409-b3a2-e55216a79ac0"
        }
    ]
}
创建一个消费者验证凭证
http://kong:8001/consumers/{consumer}/basic-auth
其中{consumer}即可以是消费者的username也可以是消费者的custom_id值
[root@contoso ~]# curl -i -X POST \
--url http://localhost:8001/consumers/jack/basic-auth \
--data "[email protected]" \
--data "password=a1b2c3d4"
HTTP/1.1 201 Created
Date: Wed, 02 May 2018 08:37:13 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{
    "created_at": 1525250233000, 
    "id": "f0d254ed-5338-403b-970b-b984d287c159", 
    "username": "[email protected]", 
    "password": "9781ab03829cd15b4c2ad37b188f2886c0beb722", 
    "consumer_id": "59fc9bc8-3149-4409-b3a2-e55216a79ac0"
}
在线base64编码工具http://tool.oschina.net/encrypt?type=3
[email protected]:a1b2c3d4 左边的键-值对字符串BASE64编码结果为:
amFja0Bob3RtYWlsLmNvbTphMWIyYzNkNA==
使用已经分配给消费的凭证进行基本验证访问 ------ 目的是删除id=2的书籍
[root@contoso ~]# curl -i -X DELETE \
--url http://localhost:8000/v1/books/2 \
--header 'Host: contoso.com' \
--header 'Authorization: Basic amFja0Bob3RtYWlsLmNvbTphMWIyYzNkNA=='

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 34
Connection: keep-alive
Date: Wed, 02 May 2018 08:55:00 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.1.13
X-Powered-By: PHP/7.1.13
X-Kong-Upstream-Latency: 28
X-Kong-Proxy-Latency: 76
Via: kong/0.13.1

{"message":"deleted successfully"}
基本验证凭证分页
[root@contoso ~]# curl -i -X GET \

--url http://localhost:8001/basic-auths

HTTP/1.1 200 OK
Date: Wed, 02 May 2018 09:17:34 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{
    "total": 1, 
    "data": [
        {
            "created_at": 1525250233000, 
            "id": "f0d254ed-5338-403b-970b-b984d287c159", 
            "password": "9781ab03829cd15b4c2ad37b188f2886c0beb722", 
            "username": "[email protected]", 
            "consumer_id": "59fc9bc8-3149-4409-b3a2-e55216a79ac0"
        }
    ]
}
获得已分配了凭证的消费者
http://kong:8001/basic-auths/{username or id}/consumer
其中{username 凭证的用户名 or id 凭证的id},注意不是消费者的用户名
[root@contoso ~]# curl -i -X GET \
--url http://localhost:8001/basic-auths/[email protected]/consumer
HTTP/1.1 200 OK
Date: Wed, 02 May 2018 09:25:50 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{
    "custom_id": "abc123", 
    "created_at": 1525248559000, 
    "username": "jack", 
    "id": "59fc9bc8-3149-4409-b3a2-e55216a79ac0"
}
获得已分配了凭证的消费者,凭证的id=f0d254ed-5338-403b-970b-b984d287c159
[root@contoso ~]# curl -i -X GET \
--url http://localhost:8001/basic-auths/f0d254ed-5338-403b-970b-b984d287c159/consumer
HTTP/1.1 200 OK
Date: Wed, 02 May 2018 09:29:32 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Server: kong/0.13.1

{
    "custom_id": "abc123", 
    "created_at": 1525248559000, 
    "username": "jack", 
    "id": "59fc9bc8-3149-4409-b3a2-e55216a79ac0"
}

猜你喜欢

转载自blog.csdn.net/zhengzizhi/article/details/80161358