1.3、Basic Authentication
支持基于用户名和密码的基本认证,通常用于简单的身份验证场景。
1.3.1、环境准备
1.3.1.1、创建一个服务,basic-auth-service
curl -i -s -X POST http://localhost:8001/services \--data name=basic-auth-service \--data url='http://localhost:8080'
http://localhost:8080 端口是运行一个Go的服务,请求/hello将返回对应的数据。
将会返回数据:
Hello, kong,I'm runing at 8080!
1.3.1.2、创建对应的路由,basic-auth-route
curl -i -X POST http://localhost:8001/services/basic-auth-service/routes \--data 'paths[]=/basic-auth' \--data name=basic-auth-route
1.3.1.3、测试环境
[root@iZbp1ivu3yaedumdy0va2vZ kong]# curl http://localhost:8000/basic-auth/hello
Hello, kong,I'm runing at 8080!
看到如下输出,证明已经环境已经搭建OK。
1.3.2 插件安装
安装basic authentication插件
1.3.2 .1、服务范围内安装
curl -X POST http://localhost:8001/services/basic-auth-service/plugins \--header "accept: application/json" \--header "Content-Type: application/json" \--data '{"name": "basic-auth","config": {"hide_credentials": true}
}'
1.3.2 .2、route范围内按照
curl -X POST http://localhost:8001/routes/basic-auth-route/plugins \--header "accept: application/json" \--header "Content-Type: application/json" \--data '{"name": "basic-auth","config": {"hide_credentials": true}
}'
1.3.2.3、全局范围安装
curl -X POST http://localhost:8001/plugins/ \--header "accept: application/json" \--header "Content-Type: application/json" \--data '{"name": "basic-auth","config": {"hide_credentials": true}
}'
1.3.3、测试插件效果
如果开启了basic-auth插件,直接访问。将会出现如下错误信息:
[root@iZbp1ivu3yaedumdy0va2vZ ~]# curl http://localhost:8000/basic-auth/hello
{"message":"Unauthorized","request_id":"c6301004ca5d8e72f932746c08a0ce44"
}
- 创建用户
curl -X POST http://localhost:8001/consumers -d username=alex
- 给用户授予basic auth权限
curl -X POST http://localhost:8001/consumers/alex/basic-auth \-d username=alex \-d password=secret123
-
执行访问
[root@iZbp1ivu3yaedumdy0va2vZ ~]# curl -u alex:secret123 http://localhost:8000/basic-auth/hello Hello, kong,I'm runing at 8080!
[root@iZbp1ivu3yaedumdy0va2vZ ~]# echo "alex:secret123" | base64 YWxleDpzZWNyZXQxMjMK [root@iZbp1ivu3yaedumdy0va2vZ ~]# curl http://localhost:8000/basic-auth/hello \-H 'Authorization: Basic YWxleDpzZWNyZXQxMjMK' Hello, kong,I'm runing at 8080!