您的位置:首页 > 编程语言 > Java开发

SPRING SESSION实现单点登录

2016-11-26 21:21 441 查看

概述

本文主要介绍利用Spring session和redis数据库实现单点登录功能。介绍了Spring session 的使用,包括从jar 包的导入,redis 数据库的配置,spring session配置文件的编写,到最后单点登录功能的实现。

实现过程

在Web项目开发中,会话管理是一个很重要的部分,用于存储与用户相关的数据。通常是由符合session规范的容器来负责存储管理,也就是一旦容器关闭,重启会导致会话失效。因此打造一个高可用性的系统,必须将session管理从容器中独立出来。而spring-session就提供了这样一个功能,可以理解spring-session是替换了Servlet那一套会话管理,既不依赖容器,又不需要改动代码,并且是用了spring-data-redis那一套连接池。在一个maven工程中实现session共享,主要有以下几个步骤(当然,前提是项目要使用Spring
Framework)。

导入相关jar包

<!-- https://mvnrepository.com/artifact/org.springframework.session/spring-session -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.orange.redis-embedded/embedded-redis -->
<dependency>
<groupId>com.orange.redis-embedded</groupId>
<artifactId>embedded-redis</artifactId>
<version>0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.session/spring-session-data-redis -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>


配置redis的连接池

确定好redis的ip和端口,然后在spring配置文件中引入
//hspaddress.properties
hsp.redis.host=localhost
hsp.redis.port=6379
hsp.redis.db=10

//spring-mvc.xml
<context:property-placeholder location="classpath:hspaddress.properties" ignore-unresolvable="true"/>

 配置spring-session(将session存储到redis数据库中)

分别在两个工程中添加spring-session.xml配置文件,因为配置文件的目的就是为了能够将session信息存储到redis,所有,配置文件都是一样的。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:annotation-config />
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:hspaddress.properties" />
</bean>
<bean id="redisHttpSessionConfiguration"
class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="3600" />
</bean>
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig" />
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="port" value="${hsp.redis.port}" />
<property name="hostName" value="${hsp.redis.host}" />
<property name="database" value="${hsp.redis.db}" />
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
<property name="keySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashValueSerializer">
<bean
class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
</bean>
<bean id="defaultCookieSerializer"
class="org.springframework.session.web.http.DefaultCookieSerializer">
<property name="cookieName" value="HSP_SESSION_ID" />
<property name="cookiePath" value="/" />
</bean>
<bean id="cookieHttpSessionStrategy"
class="org.springframework.session.web.http.CookieHttpSessionStrategy">
<property name="cookieSerializer" ref="defaultCookieSerializer" />
</bean>
4000

</beans>


在web.xml文件中添加一个session代理filter,这个filter要放在所有的filter链最前面

<filter>
<filter-name>springSessionRepositoryFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSessionRepositoryFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


测试

1、   到了这里,spring-session 配置已经基本完成。下面我们在controller中对用户登录进行验证,并且在用户session信息不存在的时候,将用户信息保存进session中,关键代码如下:

@RequestMapping("/loginAuth")
public String login(HttpServletRequest request, HttpServletResponse response,
@RequestParam Map<String, Object> params, Model model) throws UnsupportedEncodingException {
if (request.getSession().getAttribute("username") != null) {
logger.info("用户名:" + request.getSession().getAttribute("username").toString());
String userName = request.getSession().getAttribute("username").toString();
Map<String, String> user = UserUtils.getUserHap(userName);
if (user == null) {
request.setAttribute("info", "会话已失效,请重新登陆!");
logger.info(request.getAttribute("info"));
return "/login";
}
return "redirect:/";
}

if (params.get("userOid") == null || params.get("password") == null) {
return "/login";
}

String userName = params.get("userOid") == "" ? "" : params.get("userOid").toString();
String password = params.get("password") == "" ? "" : params.get("password").toString();
String url = params.get("url") == "" ? "" : params.get("url").toString();
logger.info("login params: " + params);
HttpSession session = request.getSession(false);
Map<String, String> user = UserUtils.getUserHap(userName);
logger.info(user);

if (UserUtils.authenticatePasswordHap(password, user.get("PASSWORD_ENCRYPTED"))) {
logger.info("验证通过");
session.setAttribute("userId", Long.valueOf(user.get("USER_ID")));
session.setAttribute("username", user.get("USER_NAME"));
session.setAttribute("userName", user.get("USER_NAME"));
session.setAttribute("displayName", user.get("USER_NAME"));
session.setAttribute("locale", "zh_CN");
long roleId = getUserRoleId(Long.valueOf(user.get("USER_ID")));
session.setAttribute("roleId", roleId);
session.setAttribute("timeZone", "GMT+0800");
if (request.getParameter("url") != null && !request.getParameter("url").isEmpty()
&& !"null".equals(request.getParameter("url"))) {
url = java.net.URLDecoder.decode(request.getParameter("url"), "utf-8");
System.out.println(url);
return "redirect:" + url;
}
return "dashborad";
} else {
logger.info("验证不通过");
if (userName == "" && password == "") {
request.setAttribute("info", "请输入用户名或密码!");
} else if (userName == "") {
request.setAttribute("info", "请输入用户名!");
} else if (password == "") {
request.setAttribute("info", "请输入密码!");
} else {
request.setAttribute("info", "用户名或密码错误!");
}
logger.info(request.getAttribute("info"));
return "/login";
}
}


2、   完成上述工作,我们将两个工程都部署到tomcat服务器下,启动tomcat服务器,进行以下测试:

先访问HspAdmin,在浏览器中输入localhost:8088/HspAdmin/(我的tomcat端口设置的是8088)这时因为session信息不存在,被HspAdmin这个工程中的拦截器(两个工程都设有拦截器的)拦截下来,所以我们看到 了用户登录界面。

 

关闭浏览器的标签页,在新的标签页中输入localhost:8088/ServiceMontior/同样看到用户登录界面,不过我们这次选中登录。

 

登录之后,可以看到HspServiceMontior这个工程的主界面。

 

打开浏览器新标签页,再次输入localhost:8088/HspAdmin/,这一次不一样的事情发生了,我们不再是看到用户登录界面,而是直接看到HspAdmin这个工程的主界面。

 

下面对是一个简单的分析:第一次我们访问HspAdmin,因为没有没有sessio为空,所以被拦截器拦截下来,这时我们跳到登录界面;然后我们访问HspServiceMontior,同样因为session为空,我们跳转到登录界面,当我们登录HspServiceMontior之后,这时用户信息已经被保存在session中了,而两个工程的session又都被配置成保存在redis数据库中的同一个位置,所以我们再次访问HspAdmin时,没有再跳转到登录界面,而是直接跳转到主界面,这也就间接说明spring-session配置成功。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息