Kong JWT鉴权

JWT鉴权集成

KONG-JWT

Consumers定义

The Consumer object represents a consumer - or a user - of a Service. You can either rely on Kong as the primary datastore, or you can map the consumer list with your database to keep consistency between Kong and your existing primary datastore.

​ 最简单的理解和配置consumer的方式是,将其于用户进行一一映射,即一个consumer代表一个用户(或应用).但是对于KONG而言,这些都无所谓. Consumer的核心原则是您可以为其添加插件,从而自定义他的请求行为. 所以,或许您会有一个手机APP应用,并为他的每个版本都定义一个consumer, 又或者您有一个应用或几个应用,并为这些应用定义统一个consumer,这些都无所谓.

  1. Consumer是使用Service的用户(eg: github账号就是一个Consumer是使用github Open API Service)
  2. Consumer的核心原则是您可以为其添加Plugin插件,从而自定义他的请求行为.(eg: 安装kong Oauth2插件)
  3. Consumer下可以创建多个APP(eg:您的github账号中您可以创建多个Github Apps )

使用kong-jwt首先需要一个consumer

consumers:
- username: jwt-auth-user  # 用户的唯一用户名。username或custom_id二选一。
  # custom_id: SOME_CUSTOM_ID

查看 consumer是否添加成功

curl -X GET http://localhost:8001/consumers

Response

{
  "next": null,
  "data": [
    {
      "username": "jwt-auth-user",
      "custom_id": null,
      "username_lower": null,
      "id": "3137ebac-d826-5990-b6aa-47e5187c0765",
      "updated_at": 1688025583,
      "created_at": 1688025583,
      "type": 0,
      "tags": null
    }
  ]
}

创建JWT认证

jwt_secrets:
- consumer: 'jwt-auth-user'
  algorithm: 'HS256'  # 需要根据自己的实际情况选取
  rsa_public_key: 'xxxxx'


除此之外jwt还是需要其他的参数

FIELD/PARAMETER DEFAULT DESCRIPTION
consumer
key(可选) 认证的唯一凭证 ex(Beare, Authentication)
algorithm(可选) HS256 验证签名的算法 HS256, HS384, HS512, RS256, RS384, RS512, ES256, or ES384.
rsa_public_key(可选) 用于验证签名的公钥 如果algorithmisRS256, RS384, RS512, ES256, or ES384
secret(可选) 用于验证签名的secret

校验和重启

kong config -c kong.conf parse kong.yml
kong restart -c kong.conf

查看当前用户的 jwt认证

curl -X GET http://localhost:8001/consumers/jwt-auth-user/jwt

Response

{
  "next": null,
  "data": [
    {
      "secret": "3fU90rPRIaM705g48R5lUf1ZE0iiVq4Z",
      "id": "66c44865-56a7-4331-90c3-37884e958c8c",
      "algorithm": "HS256",
      "rsa_public_key": "xxxxxx",
      "created_at": 1688030967,
      "tags": null,
      "consumer": {
        "id": "3137ebac-d826-5990-b6aa-47e5187c0765"
      },
      "key": "LMpdcxBwuQIfO2ub6IzPboIMXkNSEUqO"
    }
  ]
}

为服务添加jwt认证

services:
- name: my-service  # 服务名称
  url: localhost:8801  # 这里填写backend服务地址
  tags:
   - test-service
  plugins:
   - name: jwt
     route: upstream-api
     config:
      claims_to_verify: ["exp", "nbf"]
  routes:
  - name: ngrok-mep-server  # 路由名称
    paths:
    - /test-service  # 路由后缀名称
    



# kong.conf
/usr/local/kong/logs
    
    
log_level = notice
proxy_access_log = logs/access.log  # 代理端口请求访问的路径 相对路径
proxy_error_log = logs/error.log  # 代理端口请求错误的路径
proxy_stream_access_log = logs/access.log  # tcp流代理端口访问路径
proxy_stream_error_log = logs/error.log   # tcp流代理端口访问错误路径
admin_access_log = logs/admin_access.log
admin_error_log = logs/error.log 

你可能感兴趣的:(kong,数据库)