【web框架】【 Cloud-Admin學習筆記(三)】【ace-gate閘道器】
阿新 • • 發佈:2018-12-07
Cloud-Admin專案裡的api閘道器專案是ace-gate,採用的是Spring Cloud Gateway元件,對外提供一個統一的api入口,並實現了api鑑權的功能。
從前端專案的配置裡可以看到,所有的api請求首先都轉到localhost:8765閘道器伺服器
1、閘道器配置
轉到ace-gate配置檔案,幾處主要設定包括:
配置網關注冊到註冊中心,埠8500
consul: enabled: true host: 127.0.0.1 port: 8500 discovery: healthCheckPath: /actuator/health healthCheckInterval: 5s instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}} register: true enabled: true
api鑑權屬性 id: ace-gate, secret: 123456
auth:
serviceId: ace-auth
user:
token-header: Authorization
client:
token-header: x-client-token
id: ace-gate #不填則預設讀取spring.application.name
secret: 123456
redis和rabbitmq設定
redis: database: 2 host: 127.0.0.1 jedis: pool: max-active: 20 rabbitmq: host: ${RABBIT_MQ_HOST:localhost} port: ${RABBIT_MQ_PORT:5672} username: guest password: guest
2、攔截器
閘道器的核心邏輯是在AccessGatewayFilter,它繼承GlobalFilter介面並實現filter方法,
filter方法核心只做了3件事:
1從request請求拿到訪客的user資訊
2判斷使用者是否有許可權訪問api
3給合法的請求生成一個新的token
這個地方,前端使用者會傳來一個使用者的token,後端api鑑權也需要檢查客戶端的token,很容易讓人誤解它們是同一個token,但其實它們不是同一個值,雖然它們都是存放在head的Authorization屬性
使用者的token僅做身份認證,api的token由閘道器負責管理,不對外暴露
3、auth認證
翻看認證原始碼發現,Cloud-Admin沒有用第三方元件,自己手動實現了一個基於非對稱RSA加密的鑑權模組,
宣告AuthServerRunner繼承CommandLineRunner介面,
在鑑權伺服器啟動時,生成鑑權所需的公鑰和私鑰,並快取在redis裡,
然後用公鑰加密,私鑰解密
更底層呼叫JDK的KeyPairGenerator實現RSA非對稱加密