package com.cdzy.gateway.config; import cn.dev33.satoken.reactor.filter.SaReactorFilter; import cn.dev33.satoken.router.SaRouter; import cn.dev33.satoken.stp.StpUtil; import com.cdzy.gateway.component.AuthProperties; import jakarta.annotation.Resource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.List; /** * @author attiya * @since 2025-03-18 */ @Configuration public class SaTokenConfigure { @Value("${sa-token.is-check}") private Boolean isCheck; @Resource private AuthProperties authProperties; @Bean public SaReactorFilter getSaReactorFilter() { return new SaReactorFilter() // 拦截所有请求 .addInclude("/**") .setAuth(obj -> { if (!Boolean.TRUE.equals(isCheck)) { return; // 如果不开启校验,直接跳过 } // 1. 放行不需要鉴权的路径 SaRouter.match("/user/doLogin").free(r -> {}); SaRouter.match("/staff/ebikeOperatorStaff/login").free(r -> {}); SaRouter.match("/payment/ebikeOrder/api/**").free(r -> {}); SaRouter.match("/payment/wxPayment/api/**").free(r -> {}); SaRouter.match("/operations/ebikeBikeInfo/api/**").free(r -> {}); // 2. 对 配置文件中需要鉴权的特定路径进行校验 List requiredPaths = authProperties.getRequiredPaths(); if (requiredPaths != null && !requiredPaths.isEmpty()) { for (String path : requiredPaths) { SaRouter.match(path).check(r -> StpUtil.checkLogin()); } } // 3. 其他所有路径统一鉴权 (必须放在最后,避免覆盖前面的规则) SaRouter.match("/**") .notMatch("/user/doLogin") .notMatch("/staff/ebikeOperatorStaff/login") .notMatch("/payment/ebikeOrder/api/**") .notMatch("/payment/wxPayment/api/**") .notMatch("/operations/ebikeBikeInfo/api/**") // 排除所有 user 下的路径,只有 requiredPaths 才鉴权 .notMatch("/user/**") .check(r -> StpUtil.checkLogin()); }); } }