本文将详细讲解在若依微服务框架中集成CAS(Central Authentication Service)以实现单点登录(SSO)的配置步骤。完成集成后,将可为分布式服务提供统一的身份认证和会话管理。
首先,在auth
模块的pom.xml
文件中添加CAS
的依赖项:
<!-- CAS核心依赖 -->
<dependency>
<groupId>org.jasig.cas.client</groupId>
<artifactId>cas-client-core</artifactId>
<version>3.6.4</version>
</dependency>
在nacos
中的ruoyi-auth-dev.yml
文件(或auth
模块的bootstrap.yml
文件)中添加CAS配置,以便指定CAS服务器的登录地址和客户端配置:
cas:
enable: true
server:
url:
prefix: http://127.0.0.1:8888/cas
login: http://127.0.0.1:8888/cas/login
client:
url: http://127.0.0.1:8080/auth
在common-core
模块下的Constants.java
中添加以下内容,用于标识CAS登录成功后的状态:
public static final String CAS_TOKEN = "cas_token"; // CAS登录成功标识
public static final String WEB_TOKEN_KEY = "Cloud-Token"; // Cookie中的Token Key
public static final String WEB_TOKEN_EXPIRES = "Cloud-Expires-In"; // Cookie过期时间
在auth
模块中新建CasProperties.java
文件,以便从配置文件中读取CAS属性:
@Configuration
@RefreshScope
public class CasProperties {
@Value("{cas.enable}") private Boolean enabled;
@Value("{cas.server.url.prefix}") private String casServerUrlPrefix;
@Value("{cas.server.url.login}") private String casServerLoginUrl;
@Value("{cas.client.url}") private String serverName;
// getter 和 setter 方法
}
在auth
模块中新建NoCasFilter.java
,在未启用CAS的情况下允许所有请求直接通过:
public final class NoCasFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
}
}
在auth
模块中新建CustomSessionMappingStorage.java
,用于在单点登出时进行会话清理:
@Component
public class CustomSessionMappingStorage implements SessionMappingStorage {
private final Map<String, HttpSession> MANAGED_SESSIONS = new HashMap();
private final Map<String, String> ID_TO_SESSION_KEY_MAPPING = new HashMap();
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired private TokenService tokenService;
// 方法实现省略
}
在TokenController.java
中添加casLogin
方法,实现单点登录功能:
@GetMapping("casLogin")
public void casLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String username = request.getRemoteUser();
LoginUser userInfo = sysLoginService.login(username);
Map<String, Object> token = tokenService.createToken(userInfo);
response.addCookie(new Cookie(Constants.WEB_TOKEN_KEY, (String) token.get("access_token")));
response.sendRedirect(request.getParameter("redirect"));
}
在auth
模块中新增CasConfig.java
,实现CAS的各个过滤器及集成配置:
@Configuration
public class CasConfig {
@Autowired private CasProperties casProperties;
@Autowired private CustomSessionMappingStorage customSessionMappingStorage;
// 配置过滤器方法省略
}
在WebMvcConfig.java
中将casLogin
请求添加到白名单中,以便在未登录情况下也可访问:
public static final String[] excludeUrls = { "/casLogin", "/login", "/logout", "/refresh", "/register" };
在ruoyi-gateway-dev.yml
中将casLogin
请求放行:
ignore:
whites:
- /auth/casLogin
至此,若依微服务框架成功集成CAS,实现了单点登录功能。
powered by kaifamiao