redis同步登陆实现session共享

  今天要弄的是用redis做同步登陆,即在oa里登陆成功后即可在其它系统实现一键登陆。

   oa是用shiro登陆的,shiro里也提供了一个redis的同步session机制,不过在测试时发现,不能用,同一个请求都会产生不同的sessionid,应该是shiro底层问题,在读取sessionid时由于某些原因总是为空,于是就时不时产生一个新的sessionid,这样就没办法实现同步了,同步需要只使用一个sessionid.

   既然不用shiro的,那么就要自己来实现,就得做个filter,拦截在系统的最前面,即在shiro的filter的前面,

这里是SSOFilter.

   本来想存session到redis的,后来想到公司还有其它语言的系统,有.net的,这可能会对他们造成读取困难,那就直接以sessionid为key,userName为value存到redis里吧。

 下面上源码吧!

  RedisManager

 

Java代码   收藏代码
  1. package sy.sso;  
  2.   
  3. import java.util.Set;  
  4.   
  5. import org.slf4j.Logger;  
  6. import org.slf4j.LoggerFactory;  
  7.   
  8. import redis.clients.jedis.Jedis;  
  9. import redis.clients.jedis.JedisPool;  
  10. import redis.clients.jedis.JedisPoolConfig;  
  11. import sy.action.InitAction;  
  12.   
  13. public class RedisManager {  
  14.     private final Logger logger = LoggerFactory.getLogger(this.getClass());  
  15.     /*private String host = "172.16.6.3";*/  
  16.     private String host = "127.0.0.1";  
  17.   
  18.     private int port = 6379;  
  19.     private String dbindex = "0";  
  20.   
  21.     private String password = "123456";  
  22.     // 0 - never expire  
  23.     private int expire = 30;  
  24.     private int timeout = 2000;  
  25.   
  26.     private JedisPool jedisPool = null;  
  27.   
  28.     public RedisManager() {  
  29.           init();  
  30.     }  
  31.   
  32.     public String getPassword() {  
  33.         return password;  
  34.     }  
  35.   
  36.     public void setPassword(String password) {  
  37.         this.password = password;  
  38.     }  
  39.   
  40.     public String getDbindex() {  
  41.         return dbindex;  
  42.     }  
  43.   
  44.     public void setDbindex(String dbindex) {  
  45.         this.dbindex = dbindex;  
  46.     }  
  47.   
  48.     /** 
  49.      * 初始化方法 
  50.      */  
  51.     public void init() {  
  52.         if (jedisPool == null) {  
  53.             //jedisPool = new JedisPool(new JedisPoolConfig(), host, port, timeout, password, Integer.parseInt(dbindex));  
  54.             jedisPool = new JedisPool(new JedisPoolConfig(), host, port, timeout, null, Integer.parseInt(dbindex));  
  55.   
  56.         }  
  57.     }  
  58.   
  59.     /** 
  60.      * get value from redis 
  61.      * 
  62.      * @param key 
  63.      * @return 
  64.      */  
  65.     public byte[] get(byte[] key) {  
  66.         logger.debug("getkey:" + new String(key));  
  67.         byte[] value = null;  
  68.         Jedis jedis = jedisPool.getResource();  
  69.         try {  
  70.              jedis.auth(password);  
  71.             value = jedis.get(key);  
  72.   
  73.         } finally {  
  74.             jedisPool.returnResource(jedis);  
  75.         }  
  76.         return value;  
  77.     }  
  78.   
  79.     /** 
  80.      * 返回指定hash的field数量 
  81.      * 
  82.      * @param key 
  83.      * @return 
  84.      */  
  85.     public Long hlen(String key) {  
  86.         Long value = null;  
  87.         Jedis jedis = jedisPool.getResource();  
  88.         try {  
  89.              jedis.auth(password);  
  90.             value = jedis.hlen(key);  
  91.         } finally {  
  92.             jedisPool.returnResource(jedis);  
  93.         }  
  94.         return value;  
  95.     }  
  96.   
  97.     /** 
  98.      * 获取指定的hash field 
  99.      * 
  100.      * @param key 
  101.      * @return 
  102.      */  
  103.     public String hget(String key, String value) {  
  104.         Jedis jedis = jedisPool.getResource();  
  105.         try {  
  106.             jedis.auth(password);  
  107.             value = jedis.hget(key, value);  
  108.         } finally {  
  109.             jedisPool.returnResource(jedis);  
  110.         }  
  111.         return value;  
  112.     }  
  113.   
  114.     /** 
  115.      * 设置hash field为指定值,如果key不存在,则先创建 
  116.      * 
  117.      * @param key 
  118.      * @return 
  119.      */  
  120.     public Long hset(String key, String value1, String value2) {  
  121.         Long value = null;  
  122.         Jedis jedis = jedisPool.getResource();  
  123.         try {  
  124.             jedis.auth(password);  
  125.             value = jedis.hset(key, value1, value2);  
  126.         } finally {  
  127.             jedisPool.returnResource(jedis);  
  128.         }  
  129.         return value;  
  130.     }  
  131.   
  132.     /** 
  133.      * 添加一个string元素到,key对应的set集合中,成功返回1,如果元素以及在集合中返回0,key对应的set不存在返回错误 
  134.      * 
  135.      * @param key 
  136.      * @return 
  137.      */  
  138.     public Long sadd(String key, String value1) {  
  139.         Long value = null;  
  140.         Jedis jedis = jedisPool.getResource();  
  141.         try {  
  142.             jedis.auth(password);  
  143.             value = jedis.sadd(key, value1);  
  144.         } finally {  
  145.             jedisPool.returnResource(jedis);  
  146.         }  
  147.         return value;  
  148.     }  
  149.   
  150.     /** 
  151.      * 为key指定过期时间,单位是秒。返回1成功,0表示key已经设置过过期时间或者不存在 
  152.      * 
  153.      * @param key 
  154.      * @return 
  155.      */  
  156.     public Long expire(String key, int value1) {  
  157.         Long value = null;  
  158.         Jedis jedis = jedisPool.getResource();  
  159.         try {  
  160.             jedis.auth(password);  
  161.             value = jedis.expire(key, value1);  
  162.         } finally {  
  163.             jedisPool.returnResource(jedis);  
  164.         }  
  165.         return value;  
  166.     }  
  167.   
  168.     /** 
  169.      * 判断member是否在set中 
  170.      * 
  171.      * @param key 
  172.      * @return 
  173.      */  
  174.     public Boolean sismember(String key, String value1) {  
  175.         Boolean value = null;  
  176.         Jedis jedis = jedisPool.getResource();  
  177.         try {  
  178.             jedis.auth(password);  
  179.             value = jedis.sismember(key, value1);  
  180.         } finally {  
  181.             jedisPool.returnResource(jedis);  
  182.         }  
  183.         return value;  
  184.     }  
  185.   
  186.     /** 
  187.      * 从key对应set中移除给定元素,成功返回1,如果member在集合中不 
  188.      * 
  189.      * @param key 
  190.      * @return 
  191.      */  
  192.     public Long srem(String key, String value1) {  
  193.         Long value = null;  
  194.         Jedis jedis = jedisPool.getResource();  
  195.         try {  
  196.             jedis.auth(password);  
  197.             value = jedis.srem(key, value1);  
  198.         } finally {  
  199.             jedisPool.returnResource(jedis);  
  200.         }  
  201.         return value;  
  202.     }  
  203.   
  204.     /** 
  205.      * set 
  206.      * 
  207.      * @param key 
  208.      * @param value 
  209.      * @return 
  210.      */  
  211.     public byte[] set(byte[] key, byte[] value) {  
  212.   
  213.         Jedis jedis = jedisPool.getResource();  
  214.         try {  
  215.             jedis.auth(password);  
  216.             jedis.set(key, value);  
  217.             if (this.expire != 0) {  
  218.                 jedis.expire(key, this.expire);  
  219.             }  
  220.         } finally {  
  221.             jedisPool.returnResource(jedis);  
  222.         }  
  223.         return value;  
  224.     }  
  225.   
  226.     /** 
  227.      * set 
  228.      * 
  229.      * @param key 
  230.      * @param value 
  231.      * @param expire 
  232.      * @return 
  233.      */  
  234.     public byte[] set(byte[] key, byte[] value, int expire) {  
  235.   
  236.         Jedis jedis = jedisPool.getResource();  
  237.         try {  
  238.             jedis.auth(password);  
  239.             jedis.set(key, value);  
  240.             if (expire != 0) {  
  241.                 jedis.expire(key, expire);  
  242.             }  
  243.         } finally {  
  244.             jedisPool.returnResource(jedis);  
  245.         }  
  246.         return value;  
  247.     }  
  248.   
  249.     /** 
  250.      * del 
  251.      * 
  252.      * @param key 
  253.      */  
  254.     public void del(byte[] key) {  
  255.         Jedis jedis = jedisPool.getResource();  
  256.         try {  
  257.             jedis.auth(password);  
  258.             jedis.del(key);  
  259.         } finally {  
  260.             jedisPool.returnResource(jedis);  
  261.         }  
  262.     }  
  263.   
  264.     /** 
  265.      * flush 
  266.      */  
  267.     public void flushDB() {  
  268.         Jedis jedis = jedisPool.getResource();  
  269.         try {  
  270.             jedis.auth(password);  
  271.             jedis.flushDB();  
  272.         } finally {  
  273.             jedisPool.returnResource(jedis);  
  274.         }  
  275.     }  
  276.   
  277.     /** 
  278.      * size 
  279.      */  
  280.     public Long dbSize() {  
  281.         Long dbSize = 0L;  
  282.         Jedis jedis = jedisPool.getResource();  
  283.         try {  
  284.             jedis.auth(password);  
  285.             dbSize = jedis.dbSize();  
  286.         } finally {  
  287.             jedisPool.returnResource(jedis);  
  288.         }  
  289.         return dbSize;  
  290.     }  
  291.   
  292.     /** 
  293.      * keys 
  294.      * 
  295.      * @param regex 
  296.      * @return 
  297.      */  
  298.     public Set<byte[]> keys(String pattern) {  
  299.         Set<byte[]> keys = null;  
  300.         Jedis jedis = jedisPool.getResource();  
  301.         try {  
  302.             jedis.auth(password);  
  303.             keys = jedis.keys(pattern.getBytes());  
  304.         } finally {  
  305.             jedisPool.returnResource(jedis);  
  306.         }  
  307.         return keys;  
  308.     }  
  309.   
  310.     public String getHost() {  
  311.         return host;  
  312.     }  
  313.   
  314.     public void setHost(String host) {  
  315.         this.host = host;  
  316.     }  
  317.   
  318.     public int getPort() {  
  319.         return port;  
  320.     }  
  321.   
  322.     public void setPort(int port) {  
  323.         this.port = port;  
  324.     }  
  325.   
  326.     public int getExpire() {  
  327.         return expire;  
  328.     }  
  329.   
  330.     public void setExpire(int expire) {  
  331.         this.expire = expire;  
  332.     }  
  333.   
  334.     public static void main(String[] args) {  
  335.         // Jedis jedis = new Jedis("192.168.126.89", 6379);  
  336.         // jedis.auth("123456");  
  337.         RedisManager manager = new RedisManager();  
  338.         manager.setHost("192.168.126.89");  
  339.   
  340.         manager.init();  
  341.         for (int i = 0; i < 100000; i++) {  
  342.             // BoardItem item = new BoardItem(i+"", "clientId"+i, i, 8, 0);  
  343.             String item = i + "|" + "clientId" + i;  
  344.             manager.zadd("test", i, item);  
  345.         }  
  346.         // jedis.set("aa", "记录了");  
  347.         // System.out.println(jedis.get("aa"));  
  348.         System.out.println(manager.zrevrange("test"0100));  
  349.         System.out.println(manager.zrange("test"0100));  
  350.   
  351.     }  
  352.   
  353.     /** 
  354.      * 有序SET 添加 
  355.      * 
  356.      * @param key 
  357.      * @param score 
  358.      * @param member 
  359.      * @return 
  360.      */  
  361.     public Long zadd(String key, double score, String member) {  
  362.         Long value = null;  
  363.         Jedis jedis = jedisPool.getResource();  
  364.         try {  
  365.             jedis.auth(password);  
  366.             value = jedis.zadd(key, score, member);  
  367.         } finally {  
  368.             jedisPool.returnResource(jedis);  
  369.         }  
  370.         return value;  
  371.     }  
  372.   
  373.     public Long zrem(String key, String member) {  
  374.         Long value = null;  
  375.         Jedis jedis = jedisPool.getResource();  
  376.         try {  
  377.             jedis.auth(password);  
  378.             value = jedis.zrem(key, member);  
  379.         } finally {  
  380.             jedisPool.returnResource(jedis);  
  381.         }  
  382.         return value;  
  383.     }  
  384.   
  385.     public Set<String> zrevrange(String key, long start, long end) {  
  386.         Set<String> value = null;  
  387.         Jedis jedis = jedisPool.getResource();  
  388.         try {  
  389.             jedis.auth(password);  
  390.             value = jedis.zrevrange(key, start, end);  
  391.         } finally {  
  392.             jedisPool.returnResource(jedis);  
  393.         }  
  394.         return value;  
  395.     }  
  396.   
  397.     public Set<String> zrange(String key, long start, long end) {  
  398.         Set<String> value = null;  
  399.         Jedis jedis = jedisPool.getResource();  
  400.         try {  
  401.             jedis.auth(password);  
  402.             value = jedis.zrange(key, start, end);  
  403.         } finally {  
  404.             jedisPool.returnResource(jedis);  
  405.         }  
  406.         return value;  
  407.     }  
  408.   
  409.     public Long zrank(String key, String member) {  
  410.         Long value = null;  
  411.         Jedis jedis = jedisPool.getResource();  
  412.         try {  
  413.             jedis.auth(password);  
  414.             value = jedis.zrank(key, member);  
  415.         } finally {  
  416.             jedisPool.returnResource(jedis);  
  417.         }  
  418.         return value;  
  419.     }  
  420.   
  421.     public Long zrevrank(String key, String member) {  
  422.         Long value = null;  
  423.         Jedis jedis = jedisPool.getResource();  
  424.         try {  
  425.             jedis.auth(password);  
  426.             value = jedis.zrevrank(key, member);  
  427.         } finally {  
  428.             jedisPool.returnResource(jedis);  
  429.         }  
  430.         return value;  
  431.     }  
  432.   
  433.     public Long zcard(String key) {  
  434.         Long value = null;  
  435.         Jedis jedis = jedisPool.getResource();  
  436.         try {  
  437.             jedis.auth(password);  
  438.             value = jedis.zcard(key);  
  439.         } finally {  
  440.             jedisPool.returnResource(jedis);  
  441.         }  
  442.         return value;  
  443.     }  
  444.   
  445.     public Set<redis.clients.jedis.Tuple> zrangeWithScores(String key, long start, long end) {  
  446.         Set<redis.clients.jedis.Tuple> value = null;  
  447.         Jedis jedis = jedisPool.getResource();  
  448.         try {  
  449.             jedis.auth(password);  
  450.             value = jedis.zrangeWithScores(key, start, end);  
  451.         } finally {  
  452.             jedisPool.returnResource(jedis);  
  453.         }  
  454.         return value;  
  455.     }  
  456.   
  457.     public Set<redis.clients.jedis.Tuple> zrevrangeWithScores(String key, long start, long end) {  
  458.         Set<redis.clients.jedis.Tuple> value = null;  
  459.         Jedis jedis = jedisPool.getResource();  
  460.         try {  
  461.             jedis.auth(password);  
  462.             value = jedis.zrevrangeWithScores(key, start, end);  
  463.         } finally {  
  464.             jedisPool.returnResource(jedis);  
  465.         }  
  466.         return value;  
  467.     }  
  468.   
  469.     public Set<String> zrevrangeByScore(String key, double max, double min, int offset, int limit) {  
  470.         Set<String> value = null;  
  471.         Jedis jedis = jedisPool.getResource();  
  472.         try {  
  473.             jedis.auth(password);  
  474.             value = jedis.zrevrangeByScore(key, max, min, offset, limit);  
  475.         } finally {  
  476.             jedisPool.returnResource(jedis);  
  477.         }  
  478.         return value;  
  479.     }  
  480. }  

 RedisDAO

 

 

Java代码   收藏代码
  1. package sy.sso;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.Collection;  
  5. import java.util.HashSet;  
  6. import java.util.Set;  
  7.   
  8. import javax.servlet.http.HttpSession;  
  9.   
  10. import org.slf4j.Logger;  
  11. import org.slf4j.LoggerFactory;  
  12.   
  13. import sy.util.base.SerializeUtils;  
  14.   
  15. public class RedisDAO   {  
  16.   
  17.     private static Logger logger = LoggerFactory.getLogger(RedisDAO.class);  
  18.     /** 
  19.      * shiro-redis的session对象前缀 
  20.      */  
  21.     private final String REDIS_SESSION_PRE = "redis_session:";  
  22.   
  23.     private RedisManager redisManager;  
  24.     private int timeOut=1800000;//默认30分钟  
  25.   
  26.     public void update(String sessionid,String userName)  {  
  27.         this.save(sessionid,userName);  
  28.     }  
  29.   
  30.     /** 
  31.      * save session 
  32.      * 
  33.      * @param session 
  34.      * @throws UnknownHttpSessionException 
  35.      */  
  36.     private void save(String sessionid,String userName)  {  
  37.         if (userName == null) {  
  38.             logger.error("userName or userName id is null");  
  39.             return;  
  40.         }  
  41.   
  42.         byte[] key = getByteKey(sessionid);  
  43.         byte[] value = SerializeUtils.serialize(userName);  
  44.   
  45.   
  46.         int expire =timeOut/1000;  
  47.   
  48.         this.redisManager.set(key, value, expire);  
  49.     }  
  50.   
  51.   
  52.     public void delete(String sessionid) {  
  53.         if (sessionid == null) {  
  54.             logger.error("userName or userName id is null");  
  55.             return;  
  56.         }  
  57.         redisManager.del(this.getByteKey(sessionid));  
  58.   
  59.     }  
  60.   
  61.   
  62.     public Collection<String> getActives() {  
  63.         Set<String> userNames = new HashSet<String>();  
  64.   
  65.         Set<byte[]> keys = redisManager.keys(this.REDIS_SESSION_PRE + "*");  
  66.         if (keys != null && keys.size() > 0) {  
  67.             for (byte[] key : keys) {  
  68.                 String s = (String) SerializeUtils.deserialize(redisManager.get(key));  
  69.                 userNames.add(s);  
  70.             }  
  71.         }  
  72.   
  73.         return userNames;  
  74.     }  
  75.   
  76.   
  77.   
  78.   
  79.     public String doRead(Serializable sessionId) {  
  80.         if (sessionId == null) {  
  81.             logger.error("userName id is null");  
  82.             return null;  
  83.         }  
  84.   
  85.         String s = (String) SerializeUtils.deserialize(redisManager.get(this.getByteKey(sessionId)));  
  86.   
  87.         return s;  
  88.     }  
  89.   
  90.     /** 
  91.      * 获得byte[]型的key 
  92.      * 
  93.      * @param key 
  94.      * @return 
  95.      */  
  96.     private byte[] getByteKey(Serializable sessionid) {  
  97.         String preKey = this.REDIS_SESSION_PRE + sessionid;  
  98.         return preKey.getBytes();  
  99.     }  
  100.   
  101.     public RedisManager getRedisManager() {  
  102.         return redisManager;  
  103.     }  
  104.   
  105.     public void setRedisManager(RedisManager redisManager) {  
  106.         this.redisManager = redisManager;  
  107.   
  108.         /** 
  109.          * 初始化redisManager 
  110.          */  
  111.         this.redisManager.init();  
  112.     }  
  113.   
  114.     public int getTimeOut() {  
  115.         return timeOut;  
  116.     }  
  117.   
  118.     public void setTimeOut(int timeOut) {  
  119.         this.timeOut = timeOut;  
  120.     }  
  121.   
  122.   
  123. }  

 SSOFilter 这个类里一些装载的类如用户的那些按实际的来,只是提供模式,这里写的是本系统的,如要拿来用,请自行修改.

 

 

Java代码   收藏代码
  1. package sy.sso;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.Filter;  
  6. import javax.servlet.FilterChain;  
  7. import javax.servlet.FilterConfig;  
  8. import javax.servlet.ServletContext;  
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.ServletRequest;  
  11. import javax.servlet.ServletResponse;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15. import org.apache.commons.lang3.StringUtils;  
  16. import org.apache.log4j.Logger;  
  17. import org.apache.shiro.SecurityUtils;  
  18. import org.apache.shiro.subject.Subject;  
  19. import org.apache.shiro.subject.Subject.Builder;  
  20. import org.apache.shiro.util.ThreadContext;  
  21. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;  
  22. import org.apache.shiro.web.subject.WebSubject;  
  23. import org.hibernate.Hibernate;  
  24. import org.springframework.context.ApplicationContext;  
  25. import org.springframework.web.context.support.WebApplicationContextUtils;  
  26.   
  27. import sy.model.base.frame.SessionInfo;  
  28. import sy.model.base.frame.Syorganization;  
  29. import sy.model.base.frame.Syrole;  
  30. import sy.model.base.frame.Syuser;  
  31. import sy.model.dtom.Tuser;  
  32. import sy.service.base.frame.SyuserServiceI;  
  33. import sy.service.dtom.business.TuserServiceI;  
  34. import sy.util.base.ConfigUtil;  
  35. import sy.util.base.HqlFilter;  
  36. import sy.util.base.IpUtil;  
  37.   
  38. /** 
  39.  * 用于redis同步登陆 
  40.  * 
  41.  * @author miraclerz 
  42.  * 
  43.  */  
  44. public class SSOFilter implements Filter {  
  45.   
  46.     private static final Logger logger = Logger.getLogger(SSOFilter.class);  
  47.   
  48.     private  RedisDAO redisDAO;  
  49.     private SyuserServiceI syuserServiceI;  
  50.     private TuserServiceI tuserServiceI;  
  51.     private DefaultWebSecurityManager securityManager;  
  52.   
  53.     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
  54.         HttpServletRequest request = (HttpServletRequest) req;  
  55.         HttpServletResponse response = (HttpServletResponse) res;  
  56.   
  57.   
  58.         SessionInfo sessionInfo = null;  
  59.         if(request.getSession().getAttribute(ConfigUtil.getSessionInfoName())!=null)  
  60.         {  
  61.         sessionInfo=(SessionInfo)request.getSession().getAttribute(ConfigUtil.getSessionInfoName());  
  62.         }  
  63.   
  64.         String requestURI = request.getRequestURI();  
  65.          //取得url里的JSESSIONID  
  66.         String JSESSIONID = StringUtils.substringAfterLast(requestURI, "JSESSIONID=");  
  67.   
  68.         if(request.getSession().getAttribute("JSESSIONID")!=null)  
  69.         {//如果session里的JSESSIONID不为空,表示已经登陆了,JSESSIONID就用这个了  
  70.             JSESSIONID=(String) request.getSession().getAttribute("JSESSIONID");  
  71.         }  
  72.   
  73.          String  userName=null;  
  74.         if(sessionInfo==null&&JSESSIONID!=null&&!"".equals(JSESSIONID))  
  75.         {//如果没登陆且JSESSIONID不为空,即url地址里有JSESSIONID  
  76.           userName=redisDAO.doRead(JSESSIONID);  
  77.           logger.info(userName+":同步登陆");  
  78.         }  
  79.   
  80.         if(sessionInfo==null&&userName!=null)  
  81.         {  
  82.         HqlFilter hqlFilter = new HqlFilter();  
  83.         hqlFilter.addFilter("QUERY_t#loginname_S_EQ", userName);  
  84.         Syuser user = syuserServiceI.getByFilter(hqlFilter);  
  85.   
  86.         HqlFilter hqlFiltert = new HqlFilter();  
  87.         hqlFiltert.addFilter("QUERY_t#username_S_EQ", userName);  
  88.         Tuser tuser = tuserServiceI.getByFilter(hqlFiltert);  
  89.   
  90.         if (user != null&&tuser!=null) {  
  91.             sessionInfo = new SessionInfo();  
  92.             Hibernate.initialize(user.getSyroles());  
  93.             Hibernate.initialize(user.getSyorganizations());  
  94.             Hibernate.initialize(user.getSyresources());  
  95.             for (Syrole role : user.getSyroles()) {  
  96.                 Hibernate.initialize(role.getSyresources());  
  97.             }  
  98.             for (Syorganization organization : user.getSyorganizations()) {  
  99.                 Hibernate.initialize(organization.getSyresources());  
  100.             }  
  101.   
  102.             user.setIp(IpUtil.getIpAddr(request));  
  103.             sessionInfo.setUser(user);  
  104.   
  105.   
  106.             //同步登陆shiro  
  107.             SecurityUtils.setSecurityManager(securityManager);//  
  108.             Builder builder = new WebSubject.Builder(request,response);  
  109.             builder.authenticated(true);  
  110.             Subject subject= builder.buildSubject();  
  111.             //设置用户的session(如果不是shiro,就直接是普通的在这里设置session就行了)  
  112.             subject.getSession().setAttribute(ConfigUtil.getSessionInfoName(), sessionInfo);  
  113.             //在session里保存登陆时的sessionid,这个sessionid会存到redis里去,本系统也会一直用这个作同步  
  114.             subject.getSession().setAttribute("JSESSIONID", JSESSIONID);  
  115.             ThreadContext.bind(subject);//线程变量中绑定一个已通过验证的Subject对象  
  116.         }  
  117.         }  
  118.        if(sessionInfo!=null)  
  119.        {  
  120.            redisDAO.update(JSESSIONID,sessionInfo.getUser().getLoginname());  
  121.            System.out.println("同步session啦=>"+JSESSIONID);  
  122.        }  
  123.         chain.doFilter(request, response);  
  124.     }  
  125.   
  126.         public void init(FilterConfig filterConfig) throws ServletException {  
  127.         //这些是因为filter无法直接自动装载spring里的bean,于是用下面的方法也取得bean  
  128.         ServletContext context = filterConfig.getServletContext();  
  129.         ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);  
  130.         redisDAO = (RedisDAO) ctx.getBean("redisDAO");//直接以bean名称来取  
  131.         securityManager = (DefaultWebSecurityManager) ctx.getBean("securityManager");  
  132.         syuserServiceI=(SyuserServiceI)ctx.getBean("syuserServiceImpl");  
  133.         tuserServiceI=(TuserServiceI)ctx.getBean("tuserServiceImpl");  
  134.   
  135.       /*  String[] syuserServices=ctx.getBeanNamesForType(SyuserServiceI.class);//取得所有这个接口的实现类的bean名(以接口装载的不知道bean名是啥) 
  136.         syuserServiceI = (SyuserServiceI)ctx.getBean(syuserServices[0]);//取第一个实现类名 
  137.         logger.info("实现类名:"+syuserServices[0]); 
  138.         String[] tuserServices=ctx.getBeanNamesForType(TuserServiceI.class); 
  139.         tuserServiceI = (TuserServiceI)ctx.getBean(tuserServices[0]); 
  140. */  
  141.     }  
  142.   
  143.     public void destroy() {  
  144.     }  
  145. }  

 

  在spring 的配置文件里要加上redis的配置

Java代码   收藏代码
  1.   <bean id="redisDAO" class="sy.sso.RedisDAO">  
  2.      <property name="timeOut" value="1800000"></property>  
  3.     <property name="redisManager" >  
  4.         <bean class="sy.sso.RedisManager">  
  5.             <!-- <property name="host" value="172.16.6.3"></property> -->  
  6.             <property name="host" value="127.0.0.1"></property>  
  7.             <property name="dbindex" value="0"></property>  
  8.             <property name="password" value="123456"></property>  
  9.         </bean>  
  10.     </property>  
  11. </bean>  

 在web.xml里加上(shiro的filter的前面)

Java代码   收藏代码
  1. <!--sso同步登陆filter  -->  
  2.   <filter>  
  3.     <filter-name>ssofilter</filter-name>  
  4.     <filter-class>sy.sso.SSOFilter</filter-class>  
  5.   </filter>  
  6.   <filter-mapping>  
  7.     <filter-name>ssofilter</filter-name>  
  8.     <url-pattern>/*.sy</url-pattern>  
  9.   </filter-mapping>  
  10.   <filter-mapping>  
  11.     <filter-name>ssofilter</filter-name>  
  12.     <url-pattern>*.jsp</url-pattern>  
  13.   </filter-mapping>  

   其它系统同步时也一样是这样,配置一个ssoFilter,在这个filter里先判断是否已经登陆,如果已经登陆就直接跳过不理了,如果没登陆就判断是否地址上带有JSESSIONID,如果有就取出来,去redis里看有没有这个值,如果没有就忽略跳过,如果有就取出用户名,用这个用户名去自己的系统里把用户信息取出来,然后设置到session里就完成同步了.

在oa里还要在session的listener里对session的创建和销毁里要同步设置redis信息;

Java代码   收藏代码
  1. /** 
  2.      * 向session里增加属性时调用(用户成功登陆后会调用) 
  3.      */  
  4.     public void attributeAdded(HttpSessionBindingEvent evt) {  
  5.   
  6.         String name = evt.getName();  
  7.         logger.debug("向session存入属性:" + name);  
  8.         if (ConfigUtil.getSessionInfoName().equals(name)) {// 如果存入的属性是sessionInfo的话  
  9.             HttpSession session = evt.getSession();  
  10.             SessionInfo sessionInfo = (SessionInfo) session.getAttribute(name);  
  11.             if (sessionInfo != null) {  
  12.                 // System.out.println(sessionInfo.getUser().getName() + "登录了");  
  13.                 //SyonlineServiceI syonlineService = (SyonlineServiceI) ctx.getBean("syonlineServiceImpl");  
  14.                 Syonline online = new Syonline();  
  15.                 online.setType("1");// 登录  
  16.                 online.setLoginname(sessionInfo.getUser().getLoginname());  
  17.                 online.setIp(sessionInfo.getUser().getIp());  
  18.                 syonlineService.save(online);  
  19.                 //登陆成功后把信息存到redis  
  20.                 session.setAttribute("JSESSIONID", evt.getSession().getId());  
  21.                 redisDAO.update(evt.getSession().getId(),sessionInfo.getUser().getLoginname());  
  22.   
  23.             }  
  24.   
  25.   
  26.         }  
  27.     }  

 

Java代码   收藏代码
  1. /** 
  2.      * session销毁(用户退出系统时会调用) 
  3.      */  
  4.     public void sessionDestroyed(HttpSessionEvent evt) {  
  5.         HttpSession session = evt.getSession();  
  6.         if (session != null) {  
  7.             logger.debug("session销毁:" + session.getId());  
  8.             SessionInfo sessionInfo = (SessionInfo) session.getAttribute(ConfigUtil.getSessionInfoName());  
  9.             if (sessionInfo != null) {  
  10.                 // System.out.println(sessionInfo.getUser().getName() + "注销了");  
  11.             //  SyonlineServiceI syonlineService = (SyonlineServiceI) ctx.getBean("syonlineServiceImpl");  
  12.                 Syonline online = new Syonline();  
  13.                 online.setType("0");// 注销  
  14.                 online.setLoginname(sessionInfo.getUser().getLoginname());  
  15.                 online.setIp(sessionInfo.getUser().getIp());  
  16.                 syonlineService.save(online);  
  17.   
  18.                 //用户退出后把用户信息从redis里删除  
  19.                 Object JSESSIONID=session.getAttribute("JSESSIONID");  
  20.                 if(JSESSIONID!=null)  
  21.                 {  
  22.                     redisDAO.delete((String) JSESSIONID);  
  23.                 }  
  24.             }  
  25.         }  
  26.     }  

 

 

 

 

   跳转的地址类似这样写:

<a target="_blank" href="http://127.0.0.1:8089/oa/login.jsp;JSESSIONID=<%=request.getSession().getAttribute("JSESSIONID")%>">另一个系统go</a>

 

  OK,系统同步登陆就搞定了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值