注销登陆 清除缓存session CAS shiro redis

openEuler 22.03 安装 openGauss 5.0.2 部署手册 阅读详情

内嵌系统注销,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那边一致,否则找不到删除不掉。
到这里本次问题就差不多解决了,可能有漏记的,再继续学习补充,小白学习日记
参考了很多大佬的文章,得罪了😄,也忘了有哪些了,就不记录了。

使用 CFD 仿真进行阀门性能分析:第一部分 了解如何使用 Ansys Discovery 评估阀门性能,使工程师能够设计出更好的产品。 阅读详情

相关推荐

深度解读:车辆诊断之DTC的状态位

搞车辆诊断测试的,离不开对DTC的状态位的测试DTC的状态位是8个bit,每个bit代表不同的意思,每个bit置1或者置0都要满足一定的条件初学者,很容易被这个搞得头很大今天我们就来详细拆解一下,扫除你心中的疑惑我们以欠压故障为例进行说明,假设欠压故障(DTC code为EE0468)发生的条件如下:1. 车辆模式(CarModSts1)处于Normal(0)或者Dyno(5)2. 当电源可用性不受限制时,即ElPowerLevel (有和PwrLvlElecSubtyp组成。

帮助100万人颠覆负面潜意识,实现人生蜕变,培养1万名潜意识开发导师 1万+

SpringBoot:web项目的细节

目录 DAO层模拟数据库 设置拦截器 前端代码的抽取复用 thymeleaf的实际应用 if三元关系表达式的使用 #dates的使用 th:href 带有参数的形式 springboot 404页面的设置 用户注销 表单:日期数据上传 DAO层模拟数据库 使用map集合存储即可,增删改查均是对map的操作 @Repository public class departemtDao { private static Map<Integer, department&

qq_51476114的博客 951

STM32嵌入式开发实战:如何用miniLZO压缩算法节省70%存储空间(附完整工程)

本文详细介绍了如何在STM32嵌入式开发中使用miniLZO无损压缩算法实现高达70%的存储空间节省。通过对比分析不同轻量级算法,重点讲解miniLZO的内存优化配置、分块压缩策略和完整工程实现,帮助开发者有效解决嵌入式系统中的存储瓶颈问题。

ss78901的博客 892

CAS退出问题

CAS 3.5.2.1 版本 退出的解决方法: 1.将

海浪博客|技术|游戏|生活|随心 3266

电力远动入门:手把手解析IEC 60870-5-101规约的帧结构与报文交互(基于DL/T634.5101-2002)

本文深入解析IEC 60870-5-101规约的帧结构与报文交互,适用于电力远动通信系统。通过详细讲解规约的基础架构、控制域位定义及典型报文交互流程,帮助工程师快速掌握101规约的核心技术,提升电力自动化系统的调试与维护能力。

weixin_27076351的博客 260

为什么桥式传感器(Bridge Sensor)需要用到仪表放大器?

仪表放大器在桥式传感器的应用里起到关键作用,本文介绍桥式传感器的原理、特性,以及信号调理过程,并附上了一个 TINA - TI 的仿真电路。

疯狂的运放 1533

Spring Security框架中踢人下线技术探索

1.背景 在某次项目的开发中,使用到了Spring Security权限框架进行后端权限开发的权限校验,底层集成Spring Session组件,非常方便的集成Redis进行分布式Session的会话集群部署。系统正式上线后,各个部署节点能够非常方便的进行集群部署,用户的Session会话信息全部保存在Redis中间件库中,开发者不用关心具体的实现,Spring Session组件已经全部集成好了。 但是在系统的用户管理模块中,提供了对系统用户账号的删除功能以及禁用功能,针对这两个功能,需求方给出的具体要求

八一菜刀的专栏 1986

从立创商城到Cadence:手把手教你实现封装格式的精准迁移

本文详细介绍了如何从立创商城获取元器件封装并精准迁移至Cadence Allegro的全流程。通过实战案例MAX31865ATP+T芯片,逐步解析Altium Designer格式转换、Cadence环境配置、封装导入验证等关键步骤,提供常见问题解决方案和效率提升技巧,帮助硬件工程师实现封装格式的高效迁移。

weixin_42519985的博客 231

基于 CAS 实现通用的单点登录解决方案(三):用户单点退出实现

原理概述 基于 CAS 单点登录系统的退出主要包含两个部分: CAS 客户端应用的退出 CAS 服务端退出登录状态 我们在 CAS 客户端应用退出后将页面重定向到服务端退出登录状态,然后通过传递过去的回跳地址跳转回客户端应用退出后跳转页面。当然,此时通过单点登录的其它客户端系统还是处于登录状态的,需要等到对应 Session 过期后才能退出,因为我们使用的 CAS 扩展包是基于 PHP 自带的 Session 实现的登录操作,生成的用于存储 Session ID 的 Cookie 完全是随机的,跟..

qq_32421489的博客 2054

71.qt quick-可伸展菜单-抽屉栏示例 通用QML界面(一键换肤)

特点: 支持动态添加item、删除item、自适应界面 附带添加删除、展开等动画 同时支持qwidget、qml加载 支持number提示(比如消息数量等) 侧边抽屉栏支持动画伸展 支持换肤、拖拽、最大化等

抵抗时间扭曲,坚持做一件有意义的事 5290

logisim中,如何设计一个位于十字路口的交通信号灯控制系统?

🏆本文收录于 《全栈 Bug 调优(实战版)》 专栏。专栏聚焦真实项目中的各类疑难 Bug,从成因剖析 → 排查路径 → 解决方案 → 预防优化全链路拆解,形成一套可复用、可沉淀的实战知识体系。无论你是初入职场的开发者,还是负责复杂项目的资深工程师,都可以在这里构建一套属于自己的「问题诊断与性能调优」方法论,助你稳步进阶、放大技术价值。

**My Coding Family** 1362

CAS5.2x单点登录(九)---------cas服务端的退出源码解析以及客户端保存session及销毁session源码的解析

上一节已经说了如何解决cas客户端集群的单点退出的方法,但是由于大家对源码还不够了解,所以没有写代码上去,而我们这篇博客就是基于上篇来进一步讲解。 cas服务端的退出源码: 首先我们要找到这个jar包,因为我们是基于maven来管理这些包的,所以可以找到如下的这个包cas-server-core-logout,然后打开这个目录结构是如下所示的结构 我们一看代码并不是很多,就这区区几行,那...

java线程池 4423

【即插即用模块】卷积篇 | TGRS 2025 | HLKConv:小核+空洞=大核,感受野一致,但更轻更准!

本文介绍了分层大核卷积模块HLKConv,该模块通过动态大核+空洞卷积实现高效感受野扩展,将超大核卷积分解为小核+空洞卷积(如53×53核用17×17+dilation=3实现),计算量仅为普通大核的1/10。模块采用双分支设计:基础卷积分支捕捉局部细节,大核空洞分支捕捉长距离关联,通过1×1卷积融合。实验表明HLKConv在红外小目标检测中优于传统大核卷积,适用于高分辨率视觉任务。代码实现了不同核尺寸的配置,输入输出特征维度保持不变,计算效率显著提升。

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 357

【springboot】退出后清除session的内容并让session失效

https://blog.csdn.net/s740556472/article/details/71275328 @RequestMapping("/logout") public String logout(HttpSession session, SessionStatus sessionStatus){ session.invalidate(); sessionStat...

zx874561的博客 1万+

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

spring boot项目之登出删除缓存session至redis和cookies

一、从request中读出cookies集合,然后封装成map,为的是能够直接通过name得到相应的cookie即get方法 public static Cookie get(HttpServletRequest request, String name) { Map<String, Cookie> cookieMap = rea...

weixin_30725467的博客 2865

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

spring boot之session的创建,销毁,超时,监听等等小结

一、 session简介 1. 服务器可以为每个用户浏览器创建一个会话对象(session对象),一个浏览器只能产生一个session,当新建一个窗口访问服务器时,还是原来的那个session。session中默认保存的是当前用户的信息。因此,在需要保存其他用户数据时,我们可以自己给session添加属性。session(会话)可以看为是一种标识,通过带session的请求,可以让服务器知道是谁

east123321的博客 6万+

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

SpringBoot的httpSession(专题六)

SpringBoot的httpSession

Pleasure258的博客 2965

shiro整合ehCache,清除认证缓存

清除当前用户的shiro认证缓存(已验证) //修改成功后清除缓存 DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager)SecurityUtils.getSecurityManager(); ShiroRealm shiroRealm = (ShiroRealm) securityManager.getRealms().iterator().next(); // shiroRealm.clearAllCache();

Seven_0110的博客 1844

Spring Boot Session 会话管理示例

Spring Boot Session Management tutorial (2022) with Code Example | TechGeekNxt >> Jan 28, 2022 - In this article, we will discuss how to handle Spring Boot Sessionhttps://www.techgeeknext.com/spring-boot/spring-boot-session-management 实现 Spring Boot

allway2的博客 2973

如何清除(登录)缓存

如何清除(登录)缓存

weixin_56348428的博客 1440

强制登出所有用户,每次升级之前强制用户重新登录No SecurityManager accessible to the calling code, either bound to the org.ap

异常信息: 2021-01-07 09:39:16.299|ERROR|main|212|c.h.j.rpc.t2.util.ServiceDefinitionUtil :解析接口方法异常: method:queryTagsByCategory 2021-01-07 09:39:16.332|ERROR|main|212|c.h.j.rpc.t2.util.ServiceDefinitionUtil :解析接口方法异常: method:queryTagsByTagValue 2021-01-07 09:

java技术专家全栈成长之路 2485

总结之shiro(六)——缓存、session管理

缓存 shiro每次授权都会通过realm获取权限信息,为了提高访问速度需要添加缓存,第一次从realm中读取权限数据,之后不再读取。 缓存可以使用redis和ehcache来实现缓存 小型项目使用ehcache就可以了,很方便。 这里使用ehcache 依赖ehcache包 &lt;dependency&gt; &lt;groupId&gt;org.apache.shir...

IManiy的博客 1354

shiro缓存管理

文章目录shiro缓存现象如果我设置了缓存:缓存源码分析shiro提供的基于内存的CacheManager基于Ehcache的缓存基于Redis的缓存 shiro缓存现象 shiro缓存主要就是换成用户的授权信息,就是将我们的自定义realm的doGetAuthorizationInfo方法就是给用户授权的方法进行缓存. 如果不使用缓存,那么每次进行用户权限判断的时候就会调用一下授权方法: 我请求...

你就像甜甜的益达 1244

springboot + shiro 配置 ehcache 缓存

账号登录,第一次访问,查看控制台,有日志输出,如下所示,下面只截取了一部分的日志输出,再次访问将不再打印输出,证明缓存生效了。1、用两个浏览器分别用不同的用户登录到系统中,然后刷新界面,我们发现,无论怎么刷新,都不用有日志输出,因为此时查询的时缓存。方法,然后再刷新界面,我们发现此时后台有日志输出,即查询的数据是数据库里面的数据。方法,然后再刷新界面,我们发现此时后台有日志输出,即查询的数据是数据库里面的数据。中添加如下方法用于清除缓存,在添加或者删除权限的时候,都需要清除缓存。,并将缓存管理器添加到。

快乐的小三菊的博客 2834

SpringSession

用户第一次登录自己的账号时,服务器需要命令浏览器保存一个sessionid=xxx的cookie,以后浏览器再访问时会携带这个个cookie,前端页面也可以通过session获取用户信息。浏览器关闭之后,session会被清除。 使用步骤 1.pom引入依赖 <!-- 整合springsession --> <dependency> <groupId>org.springframework.session</g

weixin_46666822的博客 1380

spring boot——请求与参数校验——cookie&session——httpsession对象的获取&共享数据...

package org.example.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.Cookie;...

小白龙白龙马的博客 405
上一篇: No Spring Session store is configured: set the 'spring.session.store-type' property
下一篇: Mybatis执行sqlSession.insert()和sqlSession.update()需要commit
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值