若依開源管理系統采用Nacos作為配置中心,GateWay網關作為一項基本服務,也是注冊在Nacos中。
yml配置文件
網關:ruoyi-gateway-pro.yml
spring:
redis:
host: localhost
port: 6379
password:
cloud:
gateway:
discovery:
locator:
lowerCaseServiceId: true #true:只能識別小寫 false:只能識別大寫
enabled: true #開啟服務注冊發現
routes:
# 認證中心
- id: ruoyi-auth
uri: lb://ruoyi-auth
predicates:
- Path=/auth/**
filters:
# 驗證碼處理
- CacheRequestFilter
- ValidateCodeFilter
- StripPrefix=1
# 安全配置
security:
# 驗證碼
captcha:
enabled: false
type: math
# 防止XSS攻擊
xss:
enabled: true
excludeUrls:
- /system/notice
# 不校驗白名單
ignore:
whites:
- /auth/logout
- /auth/login
- /auth/register
- /*/v2/api-docs
- /csrf
可以看到,在權限認證之前,經過了多道filter進行過濾:
CacheRequestFilter
,ValidateCodeFilter
Property類
@RefreshScope
注解:該配置自動刷新(更改配置文件,即時生效)
@ConfigurationProperties
注解:可以讀取配置文件中的信息,並把它映射為實體類。
上圖中的信息是把
映射為CaptchaProperties
實體類。
config類
CaptchaConfig(驗證碼Bean)
@Bean(name = "captchaProducer")
生成了一個驗證碼bean,名字是captchaProducer
如果只用@bean
注解,未指定name
屬性,那么生成的bean名稱是getKaptchaBean
- 補充(生成bean規則)
GatewayConfig(網關限流配置)
@Order
是org.springframework.core.annotation核心包中的注解,其作用定義了Spring容器加載bean的順序。
Ordered.HIGHEST_PRECEDENCE
:初始化最高優先級,即spring容器啟動時,優先初始化添加該注解的bean
RouterFunctionConfiguration(路由配置)
- 補充(路由規則)
參考文檔:https://blog.51cto.com/u_15185289/2783813
ValidateCodeHandler
如何處理/code請求?
繼承HandlerFunction,覆寫其中的handle方法
代碼如下:
@Component
public class ValidateCodeHandler implements HandlerFunction<ServerResponse>{
@Autowired
private ValidateCodeService validateCodeService;
@Override
public Mono<ServerResponse> handle(ServerRequest serverRequest){
AjaxResult ajax;
try{
ajax = validateCodeService.createCapcha();
}catch (CaptchaException | IOException e){
return Mono.error(e);
}
return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(ajax));
}
}