内嵌系统注销,session统一注销,redis管理,单机与集群
在项目中遇到了这么一个问题,在这里记录当时解决的方式
出现的问题:系统内嵌系统,当时外系统注销用户后发现内嵌iframe的另一个系统没有退出登录,缓存仍然在,依然可以使用用户身份访问,外系统登陆另一个用户账号时,内嵌系统任然是上一次或第一次登陆的用户信息,导致用户信息不匹配和其它操作的漏洞。
调试很多次,发现问题出在由于外系统和内嵌系统session不是一个session,没有做session共享注销时CAS会通知外系统下的所有子系统退出,由于内嵌系统session没有清除而致。
解决过程:
配置文件:地址根据自己项目配置
# spring.redis
spring.redis.cluster.nodes=localhost:7001,localhost:7002,localhost:7003,localhost:7004,localhost:7005,localhost:7006
spring.redis.pool.max-active=300
spring.redis.database=0
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=100
spring.redis.pool.min-idle=20
spring.redis.timeout=60000
# redis session
spring.session.store-type=redis
# spring.cas
spring.cas.cas-server-login-url = https://localhost:7443/cas/login
spring.cas.cas-server-url-prefix = https://localhost:7443/cas
spring.cas.server-name = http://localhost/web/index
shiro-cas.casServerUrlPrefix = https://local:7443/cas
shiro-cas.casLoginUrl = ${shiro-cas.casServerUrlPrefix}/login
shiro-cas.casLogoutUrl = ${shiro-cas.casServerUrlPrefix}/logout
shiro-cas.shiroServerUrlPrefix = 内嵌的地址
shiro-cas.casFilterUrlPattern = /cas
shiro-cas.logout = ${shiro-cas.shiroServerUrlPrefix}/logout
shiro-cas.logoutFilter = /logout
shiro-cas.loginUrl = ${shiro-cas.casLoginUrl}?service=${shiro-cas.shiroServerUrlPrefix}${shiro-cas.casFilterUrlPattern}
shiro-cas.logoutUrl = ${shiro-cas.casLogoutUrl}?service=${shiro-cas.casLoginUrl}?service=${shiro-cas.shiroServerUrlPrefix}${shiro-cas.casFilterUrlPattern}
原项目没接Shiro,只用CAS做单点,修改后,将cas的配置注释掉
//@Configuration
public class CasConfig {
重新使用shiro-cas。
pom文件 注释cas-client-core,新加shiro-spring,shiro-ehcache,shiro-cas
<!--cas -->
<!--<dependency>-->
<!--<groupId>org.jasig.cas.client</groupId>-->
<!--<artifactId>cas-client-core</artifactId>-->
<!--<version>3.4.1</version>-->
<!--</dependency>-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-cas</artifactId>
<version>1.2.4</version>
</dependency>
配置类:
1.CasShiroConfig CasShiro的配置文件,常用配置,以及拦截的请求规则
package com.demo;
import org.apache.shiro.cas.CasFilter;
import org.apache.shiro.cas.CasSubjectFactory;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.jasig.cas.client.session.SingleSignOutHttpSessionListener;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;
import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
*FILE : CasShiroConfig
*DATE :
*AUTHOR
*/
@Configuration
public class CasShiroConfig {
@Autowired
ShrioCasAutoconfig autoconfig;
private String casFilterName = "casFilter";
@Bean
public MyShiroCasRealm myShiroCasRealm() {
MyShiroCasRealm realm = new MyShiroCasRealm();
realm.setCasServerUrlPrefix(autoconfig.getCasServerUrlPrefix());
/**客户端回调地址**/
realm.setCasService(autoconfig.getShiroServerUrlPrefix() + autoconfig.getCasFilterUrlPattern());
return realm;
}
/**
* 注册单点登出listener
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public ServletListenerRegistrationBean singleSignOutHttpSessionListener(){
ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean();
bean.setListener(new SingleSignOutHttpSessionListener());
bean.setEnabled(true);
return bean;
}
/**
* 注册单点登出filter
* @return
*/
@Bean
public FilterRegistrationBean singleSignOutFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setName("singleSignOutFilter");
bean.setFilter(new SingleSignOutFilterExt());
bean.addUrlPatterns("/*");
// bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
bean.setEnabled(true);
return bean;
}
/**
* 注册DelegatingFilterProxy(Shiro)
*
* @return
* @author
* @create
*/
@Bean
public FilterRegistrationBean delegatingFilterProxy() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
// 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理
filterRegistration.addInitParameter("targetFilterLifecycle", "true");
filterRegistration.setEnabled(true);
filterRegistration.addUrlPatterns("/*");
// filterRegistration.setOrder(Integer.MAX_VALUE-10);
return filterRegistration;
}
@Bean(name = "lifecycleBeanPostProcessor")
public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
daap.setProxyTargetClass(true);
return daap;
}
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(MyShiroCasRealm myShiroCasRealm) {
DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
dwsm.setRealm(myShiroCasRealm);
dwsm.setSubjectFactory(new CasSubjectFactory());
return dwsm;
}
@Bean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
aasa.setSecurityManager(securityManager);
return aasa;
}
/**
* CAS过滤器
*
* @return
* @author
* @create
*/
@Bean(name = "casFilter")
public CasFilter getCasFilter() {
CasFilter casFilter = new CasFilter();
casFilter.setName(casFilterName);
casFilter.setEnabled(true);
// 登录失败后跳转的URL,也就是 Shiro 执行 CasRealm 的 doGetAuthenticationInfo 方法向CasServer验证tiket
// 我们选择认证失败后再打开登录页面
casFilter.setFailureUrl(autoconfig.getCasLoginUrl());
return casFilter;
}
/**
* ShiroFilter
*
* 读取数据库相关配置,配置到 shiroFilterFactoryBean 的访问规则中。实际项目中,请使用自己的Service来处理业务逻辑。
*
* @param securityManager
* @param casFilter
* @return
* @author
* @create
*/
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager, CasFilter casFilter) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必须设置 SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
shiroFilterFactoryBean.setLoginUrl(autoconfig.getLoginUrl());
// 登录成功后要跳转的连接
shiroFilterFactoryBean.setSuccessUrl("/index");
// shiroFilterFactoryBean.setUnauthorizedUrl("/error");
// 添加casFilter到shiroFilter中
Map<String, Filter> filters = new HashMap<>();
filters.put("casFilter", casFilter);
// LogoutFilter logoutFilter = new LogoutFilter();
// logoutFilter.setRedirectUrl(autoconfig.getLogoutUrl());
// filters.put("logoutFilter",logoutFilter);
shiroFilterFactoryBean.setFilters(filters);
loadShiroFilterChain(shiroFilterFactoryBean);
return shiroFilterFactoryBean;
}
/**
* 加载shiroFilter权限控制规则(从数据库读取然后配置),角色/权限信息由MyShiroCasRealm对象提供doGetAuthorizationInfo实现获取来的
*
* @author
* @create
*/
private void loadShiroFilterChain(ShiroFilterFactoryBean shiroFilterFactoryBean){
/////////////////////// 下面这些规则配置最好配置到配置文件中 ///////////////////////
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
// authc:该过滤器下的页面必须登录后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter
// anon: 可以理解为不拦截
// user: 登录了就不拦截
// roles["admin"] 用户拥有admin角色
// perms["permission1"] 用户拥有permission1权限
// filter顺序按照定义顺序匹配,匹配到就验证,验证完毕结束。
// url匹配通配符支持:? * **,分别表示匹配1个,匹配0-n个(不含子路径),匹配下级所有路径
//1.shiro集成cas后,首先添加该规则
filterChainDefinitionMap.put("/cas", casFilterName);
// filterChainDefinitionMap.put("/logout","logoutFilter");
//2.不拦截的请求,根据自己两目配置
filterChainDefinitionMap.put("/static/**","anon");
filterChainDefinitionMap.put("/css/**","anon");
filterChainDefinitionMap.put("/js/**","anon");
filterChainDefinitionMap.put("/login", "anon");
// filterChainDefinitionMap.put("/logout","anon");
filterChainDefinitionMap.put("/error","anon");
filterChainDefinitionMap.put("/api/**","anon");
//3.拦截的请求(从本地数据库获取或者从casserver获取(webservice,http等远程方式),看你的角色权限配置在哪里)
//需要登录
filterChainDefinitionMap.put("/web/*", "authc");
//4.登录过的不拦截
filterChainDefinitionMap.put("/**", "user");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
}
}
2.自定义MyShiroCasRealm继承CasRealm
package com.demo;
import com.demo.SessionUserUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by
*/
public class MyShiroCasRealm extends CasRealm {
// @Autowired
// protected UserService userService;
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 权限认证,为当前登录的Subject授予角色和权限
* @see :本例中该方法的调用时机为需授权资源被访问时
* @see :并且每次访问需授权资源时都会执行该方法中的逻辑,这表明本例中默认并未启用AuthorizationCache
* @see :如果连续访问同一个URL(比如刷新),该方法不会被重复调用,Shiro有一个时间间隔(也就是cache时间,在ehcache-shiro.xml中配置),超过这个时间间隔再刷新页面,该方法会被执行
*/
@SuppressWarnings("unchecked")
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
System.out.println(SessionUserUtil.getCurrentUsername());
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo authc = super.doGetAuthenticationInfo(token);
String userName = (String) authc.getPrincipals().getPrimaryPrincipal();
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
// 可在此处理session塞入一些需要的信息
return authc;
}
}
3.RedisSessionConfig 里面又CAS过期时间的配置
package com.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 28800)
public class RedisSessionConfig {
}
4.ShrioCasAutoconfig shiro-cas的配置,配置文件中读取加载配置进config,CAS退出、登陆的Url
package com.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Created
*/
@Component
@ConfigurationProperties(prefix = "shiro-cas")
public class ShrioCasAutoconfig {
private String casServerUrlPrefix;
private String casLoginUrl;
private String casLogoutUrl;
private String shiroServerUrlPrefix;
private String casFilterUrlPattern;
private String loginUrl;
private String logoutUrl;
private String logout;
public String getCasServerUrlPrefix() {
return casServerUrlPrefix;
}
public void setCasServerUrlPrefix(String casServerUrlPrefix) {
this.casServerUrlPrefix = casServerUrlPrefix;
}
public String getCasLoginUrl() {
return casLoginUrl;
}
public void setCasLoginUrl(String casLoginUrl) {
this.casLoginUrl = casLoginUrl;
}
public String getCasLogoutUrl() {
return casLogoutUrl;
}
public void setCasLogoutUrl(String casLogoutUrl) {
this.casLogoutUrl = casLogoutUrl;
}
public String getShiroServerUrlPrefix() {
return shiroServerUrlPrefix;
}
public void setShiroServerUrlPrefix(String shiroServerUrlPrefix) {
this.shiroServerUrlPrefix = shiroServerUrlPrefix;
}
public String getCasFilterUrlPattern() {
return casFilterUrlPattern;
}
public void setCasFilterUrlPattern(String casFilterUrlPattern) {
this.casFilterUrlPattern = casFilterUrlPattern;
}
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
public String getLogoutUrl() {
return logoutUrl;
}
public void setLogoutUrl(String logoutUrl) {
this.logoutUrl = logoutUrl;
}
public String getLogout() {
return logout;
}
public void setLogout(String logout) {
this.logout = logout;
}
}
5.SingleSignOutExtHandler 登出过滤的处理
handler.isTokenRequest(request)方法:判断参数中是否具有artifactParameterName属性指定的参数名称,默认是ticket在SingleSignOutFilterExt.java中配置 。如果存在,在redis中记录session。
handler.isLogoutRequest(request):判断是否具有logoutParameterName参数指定参数,默认logoutRequest在SingleSignOutFilterExt.java中配置。如果存在,则在redis中删除记录,注销session。
recordSession: 保存session,其中addRedisHash方法中,注释掉的是单机redis方式
removeRedisLoginInfoByTicket方法:通过存储的票据(Ticket)删除登陆时存入的信息以及退出用户的票据。相当于我们在登陆的时候,为了可以找到登陆的session,多存了一个redisHash,以项目名称和ticket为key,session为value,退出的时候将两个地方同时删除。
package com.demo;
import com.demo.JedisUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.cas.client.session.HashMapBackedSessionMappingStorage;
import org.jasig.cas.client.session.SessionMappingStorage;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.util.XmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisCluster;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* Performs CAS single sign-out operations in an API-agnostic fashion.
*
* @author Marvin S. Addison
* @version $Revision$ $Date$
* @since 3.1.12
*
*/
public final class SingleSignOutExtHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(SingleSignOutExtHandler.class);
/** Logger instance */
private final Log log = LogFactory.getLog(getClass());
/** Mapping of token IDs and session IDs to HTTP sessions */
private SessionMappingStorage sessionMappingStorage = new HashMapBackedSessionMappingStorage();
/** The name of the artifact parameter. This is used to capture the session identifier. */
private String artifactParameterName = "ticket";
/** Parameter name that stores logout request */
private String logoutParameterName = "logoutRequest";
public void setSessionMappingStorage(final SessionMappingStorage storage) {
this.sessionMappingStorage = storage;
}
public SessionMappingStorage getSessionMappingStorage() {
return this.sessionMappingStorage;
}
/**
* @param name Name of the authentication token parameter.
*/
public void setArtifactParameterName(final String name) {
this.artifactParameterName = name;
}
/**
* @param name Name of parameter containing CAS logout request message.
*/
public void setLogoutParameterName(final String name) {
this.logoutParameterName = name;
}
/**
* Initializes the component for use.
*/
public void init() {
CommonUtils.assertNotNull(this.artifactParameterName, "artifactParameterName cannot be null.");
CommonUtils.assertNotNull(this.logoutParameterName, "logoutParameterName cannot be null.");
CommonUtils.assertNotNull(this.sessionMappingStorage, "sessionMappingStorage cannote be null.");
}
/**
* Determines whether the given request contains an authentication token.
*
* @param request HTTP reqest.
*
* @return True if request contains authentication token, false otherwise.
*/
public boolean isTokenRequest(final HttpServletRequest request) {
return CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.artifactParameterName));
}
/**
* Determines whether the given request is a CAS logout request.
*
* @param request HTTP request.
*
* @return True if request is logout request, false otherwise.
*/
public boolean isLogoutRequest(final HttpServletRequest request) {
return "POST".equals(request.getMethod()) && !isMultipartRequest(request) &&
CommonUtils.isNotBlank(CommonUtils.safeGetParameter(request, this.logoutParameterName));
}
/**
* Associates a token request with the current HTTP session by recording the mapping
* in the the configured {@link SessionMappingStorage} container.
*
* @param request HTTP request containing an authentication token.
*/
public void recordSession(final HttpServletRequest request) {
final HttpSession session = request.getSession(true);
final String token = CommonUtils.safeGetParameter(request, this.artifactParameterName);
if (log.isDebugEnabled()) {
log.debug("Recording session for token " + token);
}
try {
this.sessionMappingStorage.removeBySessionById(session.getId());
} catch (final Exception e) {
// ignore if the session is already marked as invalid. Nothing we can do!
}
sessionMappingStorage.addSessionById(token, session);
addRedisHash(token, token, session.getId());
}
/**
* Destroys the current HTTP session for the given CAS logout request.
*
* @param request HTTP request containing a CAS logout message.
*/
public void destroySession(final HttpServletRequest request) {
final String logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName);
if (log.isTraceEnabled()) {
log.trace ("Logout request:\n" + logoutMessage);
}
final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex");
if (CommonUtils.isNotBlank(token)) {
final HttpSession session = this.sessionMappingStorage.removeSessionByMappingId(token);
if (session != null) {
String sessionID = session.getId();
if (log.isDebugEnabled()) {
log.debug ("Invalidating session [" + sessionID + "] for token [" + token + "]");
}
try {
session.invalidate();
} catch (final IllegalStateException e) {
log.debug("Error invalidating session.", e);
}
}
}
//根据ticket,查找到对应的sessionID,并从redis中清除
removeRedisLoginInfoByTicket(token);
}
private boolean isMultipartRequest(final HttpServletRequest request) {
return request.getContentType() != null && request.getContentType().toLowerCase().startsWith("multipart");
}
private void addRedisHash(String hash, String key, String value) {
new Thread(new Runnable() {
//需要获取项目名称,以便在缓存中可以取到
String applicationName = SpringUtilExt.getPropertyValue("spring.application.name");
@Override
public void run() {
// JedisConnectionFactory jedisConnectionFactory = SpringUtilExt.getBean(JedisConnectionFactory.class);
// RedisConnection redisConnection = jedisConnectionFactory.getConnection();
// hash的名称是类似bcs:ST-8142-Qy1cb554R9dJBXtbaEBV-cas01.example.org
// ((Jedis)redisConnection.getNativeConnection()).hset(applicationName + ":" + hash, key, value);
// LOGGER.info("add to redis hash {}:{}->{}", new Object[]{applicationName + ":" + hash, key, value});
// redisConnection.close();
try{
JedisUtil.setHashJedisCluster(applicationName + ":" + hash, key, value);
LOGGER.info("add to redis hash {}:{}->{}", new Object[]{applicationName + ":" + hash, key, value});
}catch (Exception e){
LOGGER.info("==========增加session异常",e);
}
}
}).start();
}
private void removeRedisLoginInfoByTicket(String token) {
new Thread(new Runnable() {
@Override
public void run() {
// JedisConnectionFactory jedisConnectionFactory = SpringUtilExt.getBean(JedisConnectionFactory.class);
// Jedis jedisConnection = (Jedis)jedisConnectionFactory.getConnection().getNativeConnection();
String applicationName = SpringUtilExt.getPropertyValue("spring.application.name");
// String sessionId = jedisConnection.hget(applicationName + ":" +token, token);
try{
JedisCluster jedisCluster = JedisUtil.getJedisClusterConnection();
String sessionId = jedisCluster.hget(applicationName + ":" +token, token);
LOGGER.info("获取到自定义中ticket:{}对应的sessionId:{}", new Object[]{token, sessionId});
String casRedisHash = "spring:session:" + applicationName + ":sessions:" + sessionId;
jedisCluster.del(casRedisHash);
LOGGER.info("成功删除redis中cas存储的hash{}", new Object[]{casRedisHash});
jedisCluster.del(applicationName + ":"+token);
LOGGER.info("成功删除自定义cas存储的hash{}", new Object[]{applicationName + ":"+token});
jedisCluster.close();
}catch (Exception e){
LOGGER.info("清除session方法异常,{}",e);
}
}
}).start();
}
}
6.SingleSignOutFilterExt
doFilter方法中判断分支判断handler进入登陆时保存或者时登出时注销,或者是已经登陆过,进行不同处理。
package com.demo;
import org.jasig.cas.client.session.SessionMappingStorage;
import org.jasig.cas.client.util.AbstractConfigurationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* Implements the Single Sign Out protocol. It handles registering the session and destroying the session.
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.1
*/
public final class SingleSignOutFilterExt extends AbstractConfigurationFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(SingleSignOutFilterExt.class);
private static final SingleSignOutExtHandler handler = new SingleSignOutExtHandler();
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
if (!isIgnoreInitConfiguration()) {
handler.setArtifactParameterName(getPropertyFromInitParams(filterConfig, "artifactParameterName", "ticket"));
handler.setLogoutParameterName(getPropertyFromInitParams(filterConfig, "logoutParameterName", "logoutRequest"));
}
handler.init();
}
public void setArtifactParameterName(final String name) {
handler.setArtifactParameterName(name);
}
public void setLogoutParameterName(final String name) {
handler.setLogoutParameterName(name);
}
public void setSessionMappingStorage(final SessionMappingStorage storage) {
handler.setSessionMappingStorage(storage);
}
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
if (handler.isTokenRequest(request)) {
handler.recordSession(request);
} else if (handler.isLogoutRequest(request)) {
handler.destroySession(request);
// Do not continue up filter chain
return;
} else {
log.trace("Ignoring URI " + request.getRequestURI());
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
// nothing to do
}
protected static SingleSignOutExtHandler getSingleSignOutHandler() {
return handler;
}
}
7.SpringCasAutoConfig spring.cas的配置
package com.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
* Created with IntelliJ IDEA.
*
* @author:
* @date:
* Description:
*/
@Component
@ConfigurationProperties(prefix = "spring.cas")
public class SpringCasAutoConfig {
private static final String SEPARATOR = ",";
private String validateFilters;
private String signOutFilters;
private String authFilters;
private String assertionFilters;
private String requestWrapperFilters;
private String casServerUrlPrefix;
private String casServerLoginUrl;
private String serverName;
private boolean useSession = true;
private boolean redirectAfterValidation = true;
public List<String> getValidateFilters() {
return Arrays.asList(validateFilters.split(SEPARATOR));
}
public void setValidateFilters(String validateFilters) {
this.validateFilters = validateFilters;
}
public List<String> getSignOutFilters() {
return Arrays.asList(signOutFilters.split(SEPARATOR));
}
public void setSignOutFilters(String signOutFilters) {
this.signOutFilters = signOutFilters;
}
public List<String> getAuthFilters() {
return Arrays.asList(authFilters.split(SEPARATOR));
}
public void setAuthFilters(String authFilters) {
this.authFilters = authFilters;
}
public List<String> getAssertionFilters() {
return Arrays.asList(assertionFilters.split(SEPARATOR));
}
public void setAssertionFilters(String assertionFilters) {
this.assertionFilters = assertionFilters;
}
public List<String> getRequestWrapperFilters() {
return Arrays.asList(requestWrapperFilters.split(SEPARATOR));
}
public void setRequestWrapperFilters(String requestWrapperFilters) {
this.requestWrapperFilters = requestWrapperFilters;
}
public String getCasServerUrlPrefix() {
return casServerUrlPrefix;
}
public void setCasServerUrlPrefix(String casServerUrlPrefix) {
this.casServerUrlPrefix = casServerUrlPrefix;
}
public String getCasServerLoginUrl() {
return casServerLoginUrl;
}
public void setCasServerLoginUrl(String casServerLoginUrl) {
this.casServerLoginUrl = casServerLoginUrl;
}
public String getServerName() {
return serverName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public boolean isRedirectAfterValidation() {
return redirectAfterValidation;
}
public void setRedirectAfterValidation(boolean redirectAfterValidation) {
this.redirectAfterValidation = redirectAfterValidation;
}
public boolean isUseSession() {
return useSession;
}
public void setUseSession(boolean useSession) {
this.useSession = useSession;
}
}
8.SpringUtilExt 工具类,可以取配置文件信息
package com.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class SpringUtilExt implements ApplicationContextAware {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringUtilExt.class);
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtilExt.applicationContext == null) {
SpringUtilExt.applicationContext = applicationContext;
}
}
//获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
//通过name获取 Bean.
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
//通过class获取Bean.
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
//通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
// 通过属性名称获取属性值
public static String getPropertyValue(String propertyKey) {
Environment env = getApplicationContext().getBean(Environment.class);
String propertyValue = env.getProperty(propertyKey);
LOGGER.info("获取到属性名称:【{}】 -> 【{}】", new Object[]{propertyKey, propertyValue});
return propertyValue;
}
}
9.redis集群方式获取jedis操作
package com.demo;
import com.demo.SpringUtilExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
*
*/
@Service
public class JedisUtil {
private static Logger logger = LoggerFactory.getLogger(JedisUtil.class);
private static String clusterNodes = SpringUtilExt.getPropertyValue("spring.redis.cluster.nodes");
public static String getClusterNodes() {
return clusterNodes;
}
/**
* 获取集群模式的redis连接信息
* @return
*/
public static JedisCluster getJedisClusterConnection(){
JedisCluster cluster = null;
Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>();
for(String item :clusterNodes.split(",")){
nodes.add(new HostAndPort(item.split(":")[0],Integer.valueOf(item.split(":")[1])));
}
try {
cluster = new JedisCluster(nodes,10000);
} catch (Exception e) {
logger.error("系统异常!",e);
}
return cluster;
}
/**
* 获取集群模式的redis连接信息
* @return
*/
public static void closeJedisClusterConnection(JedisCluster jedisCluster){
try {
jedisCluster.close();
} catch (IOException e) {
logger.error("jedis关闭异常!",e);
}
}
/**
* 从集群模式的redis中获取数据
* @param key
* @return
*/
public static String getStringFromJedisCluster(String key){
JedisCluster jedisCluster = getJedisClusterConnection();
return jedisCluster.get(key);
}
/**
* 向集群模式的redis中塞值,如果超时时间设置的<=0,认为不必设置有效期
* @param key
* @param value
* @return
*/
public static String setString2JedisCluster(String key,String value,int seconds){
JedisCluster jedisCluster = getJedisClusterConnection();
if(seconds <= 0){
return jedisCluster.set(key,value);
}else{
return jedisCluster.setex(key,seconds,value);
}
}
/**
* 向集群模式的redis中塞值,如果超时时间设置的<=0,认为不必设置有效期
* @param key
* @param value
* @return
*/
public static void setHashJedisCluster(String hash,String key,String value){
JedisCluster jedisCluster = getJedisClusterConnection();
jedisCluster.hset(hash,key,value);
try {
jedisCluster.close();
} catch (Exception e){
logger.error("系统异常!",e);
}
}
}
启动类加注解
@EnableRedisHttpSession(redisNamespace=“项目名称”,maxInactiveIntervalInSeconds = 28800)
项目名称要与存session那边一致,否则找不到删除不掉。
到这里本次问题就差不多解决了,可能有漏记的,再继续学习补充,小白学习日记
参考了很多大佬的文章,得罪了😄,也忘了有哪些了,就不记录了。
1万+




被折叠的 条评论
为什么被折叠?



