单点登录系统实现基于SpringBoot

2 篇文章 0 订阅
2 篇文章 0 订阅

转载:点击打开链接

 

今天的干货有点湿,里面夹杂着我的泪水。可能也只有代码才能让我暂时的平静。通过本章内容你将学到单点登录系统和传统登录系统的区别,单点登录系统设计思路,Spring4 Java配置方式整合HttpClient,整合SolrJ ,HttpClient简易教程。还在等什么?撸起袖子开始干吧! 
效果图:8081端口是sso系统,其他两个8082和8083端口模拟两个系统。登录成功后检查Redis数据库中是否有值。 
效果图

技术:SpringBoot,SpringMVC,Spring,SpringData,Redis,HttpClient 
说明:本章的用户登录注册的代码部分已经在SpringBoot基础入门中介绍过了,这里不会重复贴代码。 
源码:见文章底部 
SpringBoot基础入门:http://www.cnblogs.com/itdragon/p/8047132.html

单点登录系统简介

单点登录系统 
在传统的系统,或者是只有一个服务器的系统中。Session在一个服务器中,各个模块都可以直接获取,只需登录一次就进入各个模块。若在服务器集群或者是分布式系统架构中,每个服务器之间的Session并不是共享的,这会出现每个模块都要登录的情况。这时候需要通过单点登录系统(Single Sign On)将用户信息存在Redis数据库中实现Session共享的效果。从而实现一次登录就可以访问所有相互信任的应用系统。

单点登录系统实现

Maven项目核心配置文件 pom.xml 需要在原来的基础上添加 httpclient和jedis jar包

 
  1. <dependency> <!-- http client version is 4.5.3 -->

  2. <groupId>org.apache.httpcomponents</groupId>

  3. <artifactId>httpclient</artifactId>

  4. </dependency>

  5. <dependency> <!-- redis java client version is 2.9.0 -->

  6. <groupId>redis.clients</groupId>

  7. <artifactId>jedis</artifactId>

  8. </dependency>

Spring4 Java配置方式

这里,我们需要整合httpclient用于各服务之间的通讯(也可以用okhttp)。同时还需要整合redis用于存储用户信息(Session共享)。 
在Spring3.x之前,一般在应用的基本配置用xml,比如数据源、资源文件等。业务开发用注解,比如Component,Service,Controller等。其实在Spring3.x的时候就已经提供了Java配置方式。现在的Spring4.x和SpringBoot都开始推荐使用Java配置方式配置bean。它可以使bean的结构更加的清晰。

整合 HttpClient

HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。 
HttpClient4.5系列教程 : http://blog.csdn.net/column/details/httpclient.html

首先在src/main/resources 目录下创建 httpclient.properties 配置文件

 
  1. #设置整个连接池默认最大连接数

  2. http.defaultMaxPerRoute=100

  3. #设置整个连接池最大连接数

  4. http.maxTotal=300

  5. #设置请求超时

  6. http.connectTimeout=1000

  7. #设置从连接池中获取到连接的最长时间

  8. http.connectionRequestTimeout=500

  9. #设置数据传输的最长时间

  10. http.socketTimeout=10000

然后在 src/main/java/com/itdragon/config 目录下创建 HttpclientSpringConfig.java 文件 
这里用到了四个很重要的注解 
@Configuration : 作用于类上,指明该类就相当于一个xml配置文件 
@Bean : 作用于方法上,指明该方法相当于xml配置中的,注意方法名的命名规范 
@PropertySource : 指定读取的配置文件,引入多个value={“xxx:xxx”,”xxx:xxx”},ignoreResourceNotFound=true 文件不存在是忽略 
@Value : 获取配置文件的值,该注解还有很多语法知识,这里暂时不扩展开

 
  1. package com.itdragon.config;

  2.  
  3. import java.util.concurrent.TimeUnit;

  4. import org.apache.http.client.config.RequestConfig;

  5. import org.apache.http.impl.client.CloseableHttpClient;

  6. import org.apache.http.impl.client.HttpClients;

  7. import org.apache.http.impl.client.IdleConnectionEvictor;

  8. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

  9. import org.springframework.beans.factory.annotation.Autowired;

  10. import org.springframework.beans.factory.annotation.Value;

  11. import org.springframework.context.annotation.Bean;

  12. import org.springframework.context.annotation.Configuration;

  13. import org.springframework.context.annotation.PropertySource;

  14. import org.springframework.context.annotation.Scope;

  15.  
  16. /**

  17. * @Configuration 作用于类上,相当于一个xml配置文件

  18. * @Bean 作用于方法上,相当于xml配置中的<bean>

  19. * @PropertySource 指定读取的配置文件

  20. * @Value 获取配置文件的值

  21. */

  22. @Configuration

  23. @PropertySource(value = "classpath:httpclient.properties")

  24. public class HttpclientSpringConfig {

  25.  
  26. @Value("${http.maxTotal}")

  27. private Integer httpMaxTotal;

  28.  
  29. @Value("${http.defaultMaxPerRoute}")

  30. private Integer httpDefaultMaxPerRoute;

  31.  
  32. @Value("${http.connectTimeout}")

  33. private Integer httpConnectTimeout;

  34.  
  35. @Value("${http.connectionRequestTimeout}")

  36. private Integer httpConnectionRequestTimeout;

  37.  
  38. @Value("${http.socketTimeout}")

  39. private Integer httpSocketTimeout;

  40.  
  41. @Autowired

  42. private PoolingHttpClientConnectionManager manager;

  43.  
  44. @Bean

  45. public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {

  46. PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();

  47. // 最大连接数

  48. poolingHttpClientConnectionManager.setMaxTotal(httpMaxTotal);

  49. // 每个主机的最大并发数

  50. poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpDefaultMaxPerRoute);

  51. return poolingHttpClientConnectionManager;

  52. }

  53.  
  54. @Bean // 定期清理无效连接

  55. public IdleConnectionEvictor idleConnectionEvictor() {

  56. return new IdleConnectionEvictor(manager, 1L, TimeUnit.HOURS);

  57. }

  58.  
  59. @Bean // 定义HttpClient对象 注意该对象需要设置scope="prototype":多例对象

  60. @Scope("prototype")

  61. public CloseableHttpClient closeableHttpClient() {

  62. return HttpClients.custom().setConnectionManager(this.manager).build();

  63. }

  64.  
  65. @Bean // 请求配置

  66. public RequestConfig requestConfig() {

  67. return RequestConfig.custom().setConnectTimeout(httpConnectTimeout) // 创建连接的最长时间

  68. .setConnectionRequestTimeout(httpConnectionRequestTimeout) // 从连接池中获取到连接的最长时间

  69. .setSocketTimeout(httpSocketTimeout) // 数据传输的最长时间

  70. .build();

  71. }

  72. }

整合 Redis

SpringBoot官方其实提供了spring-boot-starter-redis pom 帮助我们快速开发,但我们也可以自定义配置,这样可以更方便地掌控。 
Redis 系列教程 : http://www.cnblogs.com/itdragon/category/1122427.html

首先在src/main/resources 目录下创建 redis.properties 配置文件 
设置Redis主机的ip地址和端口号,和存入Redis数据库中的key以及存活时间。这里为了方便测试,存活时间设置的比较小。这里的配置是单例Redis。

 
  1. redis.node.host=192.168.225.131

  2. redis.node.port=6379

  3.  
  4. REDIS_USER_SESSION_KEY=REDIS_USER_SESSION

  5. SSO_SESSION_EXPIRE=30

在src/main/java/com/itdragon/config 目录下创建 RedisSpringConfig.java 文件

 
  1. package com.itdragon.config;

  2.  
  3. import java.util.ArrayList;

  4. import java.util.List;

  5. import org.springframework.beans.factory.annotation.Value;

  6. import org.springframework.context.annotation.Bean;

  7. import org.springframework.context.annotation.Configuration;

  8. import org.springframework.context.annotation.PropertySource;

  9. import redis.clients.jedis.JedisPool;

  10. import redis.clients.jedis.JedisPoolConfig;

  11. import redis.clients.jedis.JedisShardInfo;

  12. import redis.clients.jedis.ShardedJedisPool;

  13.  
  14. @Configuration

  15. @PropertySource(value = "classpath:redis.properties")

  16. public class RedisSpringConfig {

  17.  
  18. @Value("${redis.maxTotal}")

  19. private Integer redisMaxTotal;

  20.  
  21. @Value("${redis.node.host}")

  22. private String redisNodeHost;

  23.  
  24. @Value("${redis.node.port}")

  25. private Integer redisNodePort;

  26.  
  27. private JedisPoolConfig jedisPoolConfig() {

  28. JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

  29. jedisPoolConfig.setMaxTotal(redisMaxTotal);

  30. return jedisPoolConfig;

  31. }

  32.  
  33. @Bean

  34. public JedisPool getJedisPool(){ // 省略第一个参数则是采用 Protocol.DEFAULT_DATABASE

  35. JedisPool jedisPool = new JedisPool(jedisPoolConfig(), redisNodeHost, redisNodePort);

  36. return jedisPool;

  37. }

  38.  
  39. @Bean

  40. public ShardedJedisPool shardedJedisPool() {

  41. List<JedisShardInfo> jedisShardInfos = new ArrayList<JedisShardInfo>();

  42. jedisShardInfos.add(new JedisShardInfo(redisNodeHost, redisNodePort));

  43. return new ShardedJedisPool(jedisPoolConfig(), jedisShardInfos);

  44. }

  45. }

Service 层

在src/main/java/com/itdragon/service 目录下创建 UserService.java 文件,它负责三件事情 
第一件事件:验证用户信息是否正确,并将登录成功的用户信息保存到Redis数据库中。 
第二件事件:负责判断用户令牌是否过期,若没有则刷新令牌存活时间。 
第三件事件:负责从Redis数据库中删除用户信息。 
这里用到了一些工具类,不影响学习,可以从源码中直接获取。

 
  1. package com.itdragon.service;

  2.  
  3. import java.util.UUID;

  4. import javax.servlet.http.HttpServletRequest;

  5. import javax.servlet.http.HttpServletResponse;

  6. import javax.transaction.Transactional;

  7. import org.springframework.beans.factory.annotation.Autowired;

  8. import org.springframework.beans.factory.annotation.Value;

  9. import org.springframework.context.annotation.PropertySource;

  10. import org.springframework.stereotype.Service;

  11. import org.springframework.util.StringUtils;

  12. import com.itdragon.pojo.ItdragonResult;

  13. import com.itdragon.pojo.User;

  14. import com.itdragon.repository.JedisClient;

  15. import com.itdragon.repository.UserRepository;

  16. import com.itdragon.utils.CookieUtils;

  17. import com.itdragon.utils.ItdragonUtils;

  18. import com.itdragon.utils.JsonUtils;

  19. @Service

  20. @Transactional

  21. @PropertySource(value = "classpath:redis.properties")

  22. public class UserService {

  23.  
  24. @Autowired

  25. private UserRepository userRepository;

  26.  
  27. @Autowired

  28. private JedisClient jedisClient;

  29.  
  30. @Value("${REDIS_USER_SESSION_KEY}")

  31. private String REDIS_USER_SESSION_KEY;

  32.  
  33. @Value("${SSO_SESSION_EXPIRE}")

  34. private Integer SSO_SESSION_EXPIRE;

  35.  
  36. public ItdragonResult userLogin(String account, String password,

  37. HttpServletRequest request, HttpServletResponse response) {

  38. // 判断账号密码是否正确

  39. User user = userRepository.findByAccount(account);

  40. if (!ItdragonUtils.decryptPassword(user, password)) {

  41. return ItdragonResult.build(400, "账号名或密码错误");

  42. }

  43. // 生成token

  44. String token = UUID.randomUUID().toString();

  45. // 清空密码和盐避免泄漏

  46. String userPassword = user.getPassword();

  47. String userSalt = user.getSalt();

  48. user.setPassword(null);

  49. user.setSalt(null);

  50. // 把用户信息写入 redis

  51. jedisClient.set(REDIS_USER_SESSION_KEY + ":" + token, JsonUtils.objectToJson(user));

  52. // user 已经是持久化对象,被保存在session缓存当中,若user又重新修改属性值,那么在提交事务时,此时 hibernate对象就会拿当前这个user对象和保存在session缓存中的user对象进行比较,如果两个对象相同,则不会发送update语句,否则会发出update语句。

  53. user.setPassword(userPassword);

  54. user.setSalt(userSalt);

  55. // 设置 session 的过期时间

  56. jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);

  57. // 添加写 cookie 的逻辑,cookie 的有效期是关闭浏览器就失效。

  58. CookieUtils.setCookie(request, response, "USER_TOKEN", token);

  59. // 返回token

  60. return ItdragonResult.ok(token);

  61. }

  62.  
  63. public void logout(String token) {

  64. jedisClient.del(REDIS_USER_SESSION_KEY + ":" + token);

  65. }

  66.  
  67. public ItdragonResult queryUserByToken(String token) {

  68. // 根据token从redis中查询用户信息

  69. String json = jedisClient.get(REDIS_USER_SESSION_KEY + ":" + token);

  70. // 判断是否为空

  71. if (StringUtils.isEmpty(json)) {

  72. return ItdragonResult.build(400, "此session已经过期,请重新登录");

  73. }

  74. // 更新过期时间

  75. jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);

  76. // 返回用户信息

  77. return ItdragonResult.ok(JsonUtils.jsonToPojo(json, User.class));

  78. }

  79. }

Controller 层

负责跳转登录页面跳转

 
  1. package com.itdragon.controller;

  2.  
  3. import org.springframework.stereotype.Controller;

  4. import org.springframework.ui.Model;

  5. import org.springframework.web.bind.annotation.RequestMapping;

  6.  
  7. @Controller

  8. public class PageController {

  9.  
  10. @RequestMapping("/login")

  11. public String showLogin(String redirect, Model model) {

  12. model.addAttribute("redirect", redirect);

  13. return "login";

  14. }

  15.  
  16. }

负责用户的登录,退出,获取令牌的操作

 
  1. package com.itdragon.controller;

  2.  
  3. import javax.servlet.http.HttpServletRequest;

  4. import javax.servlet.http.HttpServletResponse;

  5. import org.springframework.beans.factory.annotation.Autowired;

  6. import org.springframework.stereotype.Controller;

  7. import org.springframework.web.bind.annotation.PathVariable;

  8. import org.springframework.web.bind.annotation.RequestMapping;

  9. import org.springframework.web.bind.annotation.RequestMethod;

  10. import org.springframework.web.bind.annotation.ResponseBody;

  11. import com.itdragon.pojo.ItdragonResult;

  12. import com.itdragon.service.UserService;

  13.  
  14. @Controller

  15. @RequestMapping("/user")

  16. public class UserController {

  17.  
  18. @Autowired

  19. private UserService userService;

  20.  
  21. @RequestMapping(value="/login", method=RequestMethod.POST)

  22. @ResponseBody

  23. public ItdragonResult userLogin(String username, String password,

  24. HttpServletRequest request, HttpServletResponse response) {

  25. try {

  26. ItdragonResult result = userService.userLogin(username, password, request, response);

  27. return result;

  28. } catch (Exception e) {

  29. e.printStackTrace();

  30. return ItdragonResult.build(500, "");

  31. }

  32. }

  33.  
  34. @RequestMapping(value="/logout/{token}")

  35. public String logout(@PathVariable String token) {

  36. userService.logout(token); // 思路是从Redis中删除key,实际情况请和业务逻辑结合

  37. return "index";

  38. }

  39.  
  40. @RequestMapping("/token/{token}")

  41. @ResponseBody

  42. public Object getUserByToken(@PathVariable String token) {

  43. ItdragonResult result = null;

  44. try {

  45. result = userService.queryUserByToken(token);

  46. } catch (Exception e) {

  47. e.printStackTrace();

  48. result = ItdragonResult.build(500, "");

  49. }

  50. return result;

  51. }

  52. }

视图层

一个简单的登录页面

 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"

  2. pageEncoding="UTF-8"%>

  3. <!doctype html>

  4. <html lang="zh">

  5. <head>

  6. <meta name="viewport" content="initial-scale=1.0, width=device-width, user-scalable=no" />

  7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  8. <meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1" />

  9. <meta http-equiv="X-UA-Compatible" content="IE=8" />

  10. <title>欢迎登录</title>

  11. <link type="image/x-icon" href="images/favicon.ico" rel="shortcut icon">

  12. <link rel="stylesheet" href="static/css/main.css" />

  13. </head>

  14. <body>

  15. <div class="wrapper">

  16. <div class="container">

  17. <h1>Welcome</h1>

  18. <form method="post" onsubmit="return false;" class="form">

  19. <input type="text" value="itdragon" name="username" placeholder="Account"/>

  20. <input type="password" value="123456789" name="password" placeholder="Password"/>

  21. <button type="button" id="login-button">Login</button>

  22. </form>

  23. </div>

  24. <ul class="bg-bubbles">

  25. <li></li>

  26. <li></li>

  27. <li></li>

  28. <li></li>

  29. <li></li>

  30. <li></li>

  31. <li></li>

  32. <li></li>

  33. <li></li>

  34. <li></li>

  35. </ul>

  36. </div>

  37. <script type="text/javascript" src="static/js/jquery-1.10.1.min.js" ></script>

  38. <script type="text/javascript">

  39. var redirectUrl = "${redirect}"; // 浏览器中返回的URL

  40. function doLogin() {

  41. $.post("/user/login", $(".form").serialize(),function(data){

  42. if (data.status == 200) {

  43. if (redirectUrl == "") {

  44. location.href = "http://localhost:8082";

  45. } else {

  46. location.href = redirectUrl;

  47. }

  48. } else {

  49. alert("登录失败,原因是:" + data.msg);

  50. }

  51. });

  52. }

  53. $(function(){

  54. $("#login-button").click(function(){

  55. doLogin();

  56. });

  57. });

  58. </script>

  59. </body>

  60. </html>

HttpClient 基础语法

这里封装了get,post请求的方法

 
  1. package com.itdragon.utils;

  2.  
  3. import java.io.IOException;

  4. import java.net.URI;

  5. import java.util.ArrayList;

  6. import java.util.List;

  7. import java.util.Map;

  8. import org.apache.http.NameValuePair;

  9. import org.apache.http.client.entity.UrlEncodedFormEntity;

  10. import org.apache.http.client.methods.CloseableHttpResponse;

  11. import org.apache.http.client.methods.HttpGet;

  12. import org.apache.http.client.methods.HttpPost;

  13. import org.apache.http.client.utils.URIBuilder;

  14. import org.apache.http.entity.ContentType;

  15. import org.apache.http.entity.StringEntity;

  16. import org.apache.http.impl.client.CloseableHttpClient;

  17. import org.apache.http.impl.client.HttpClients;

  18. import org.apache.http.message.BasicNameValuePair;

  19. import org.apache.http.util.EntityUtils;

  20.  
  21. public class HttpClientUtil {

  22.  
  23. public static String doGet(String url) { // 无参数get请求

  24. return doGet(url, null);

  25. }

  26.  
  27. public static String doGet(String url, Map<String, String> param) { // 带参数get请求

  28. CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建一个默认可关闭的Httpclient 对象

  29. String resultMsg = ""; // 设置返回值

  30. CloseableHttpResponse response = null; // 定义HttpResponse 对象

  31. try {

  32. URIBuilder builder = new URIBuilder(url); // 创建URI,可以设置host,设置参数等

  33. if (param != null) {

  34. for (String key : param.keySet()) {

  35. builder.addParameter(key, param.get(key));

  36. }

  37. }

  38. URI uri = builder.build();

  39. HttpGet httpGet = new HttpGet(uri); // 创建http GET请求

  40. response = httpClient.execute(httpGet); // 执行请求

  41. if (response.getStatusLine().getStatusCode() == 200) { // 判断返回状态为200则给返回值赋值

  42. resultMsg = EntityUtils.toString(response.getEntity(), "UTF-8");

  43. }

  44. } catch (Exception e) {

  45. e.printStackTrace();

  46. } finally { // 不要忘记关闭

  47. try {

  48. if (response != null) {

  49. response.close();

  50. }

  51. httpClient.close();

  52. } catch (IOException e) {

  53. e.printStackTrace();

  54. }

  55. }

  56. return resultMsg;

  57. }

  58.  
  59. public static String doPost(String url) { // 无参数post请求

  60. return doPost(url, null);

  61. }

  62.  
  63. public static String doPost(String url, Map<String, String> param) {// 带参数post请求

  64. CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建一个默认可关闭的Httpclient 对象

  65. CloseableHttpResponse response = null;

  66. String resultMsg = "";

  67. try {

  68. HttpPost httpPost = new HttpPost(url); // 创建Http Post请求

  69. if (param != null) { // 创建参数列表

  70. List<NameValuePair> paramList = new ArrayList<NameValuePair>();

  71. for (String key : param.keySet()) {

  72. paramList.add(new BasicNameValuePair(key, param.get(key)));

  73. }

  74. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);// 模拟表单

  75. httpPost.setEntity(entity);

  76. }

  77. response = httpClient.execute(httpPost); // 执行http请求

  78. if (response.getStatusLine().getStatusCode() == 200) {

  79. resultMsg = EntityUtils.toString(response.getEntity(), "utf-8");

  80. }

  81. } catch (Exception e) {

  82. e.printStackTrace();

  83. } finally {

  84. try {

  85. if (response != null) {

  86. response.close();

  87. }

  88. httpClient.close();

  89. } catch (IOException e) {

  90. e.printStackTrace();

  91. }

  92. }

  93. return resultMsg;

  94. }

  95.  
  96. public static String doPostJson(String url, String json) {

  97. CloseableHttpClient httpClient = HttpClients.createDefault();

  98. CloseableHttpResponse response = null;

  99. String resultString = "";

  100. try {

  101. HttpPost httpPost = new HttpPost(url);

  102. StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);

  103. httpPost.setEntity(entity);

  104. response = httpClient.execute(httpPost);

  105. if (response.getStatusLine().getStatusCode() == 200) {

  106. resultString = EntityUtils.toString(response.getEntity(), "utf-8");

  107. }

  108. } catch (Exception e) {

  109. e.printStackTrace();

  110. } finally {

  111. try {

  112. if (response != null) {

  113. response.close();

  114. }

  115. httpClient.close();

  116. } catch (IOException e) {

  117. e.printStackTrace();

  118. }

  119. }

  120. return resultString;

  121. }

  122. }

Spring 自定义拦截器

这里是另外一个项目 itdragon-service-test-sso 中的代码, 
首先在src/main/resources/spring/springmvc.xml 中配置拦截器,设置那些请求需要拦截

 
  1. <!-- 拦截器配置 -->

  2. <mvc:interceptors>

  3. <mvc:interceptor>

  4. <mvc:mapping path="/github/**"/>

  5. <bean class="com.itdragon.interceptors.UserLoginHandlerInterceptor"/>

  6. </mvc:interceptor>

  7. </mvc:interceptors>

然后在 src/main/java/com/itdragon/interceptors 目录下创建 UserLoginHandlerInterceptor.java 文件

 
  1. package com.itdragon.interceptors;

  2.  
  3. import javax.servlet.http.HttpServletRequest;

  4. import javax.servlet.http.HttpServletResponse;

  5. import org.springframework.beans.factory.annotation.Autowired;

  6. import org.springframework.util.StringUtils;

  7. import org.springframework.web.servlet.HandlerInterceptor;

  8. import org.springframework.web.servlet.ModelAndView;

  9. import com.itdragon.pojo.User;

  10. import com.itdragon.service.UserService;

  11. import com.itdragon.utils.CookieUtils;

  12.  
  13. public class UserLoginHandlerInterceptor implements HandlerInterceptor {

  14.  
  15. public static final String COOKIE_NAME = "USER_TOKEN";

  16.  
  17. @Autowired

  18. private UserService userService;

  19.  
  20. @Override

  21. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

  22. throws Exception {

  23. String token = CookieUtils.getCookieValue(request, COOKIE_NAME);

  24. User user = this.userService.getUserByToken(token);

  25. if (StringUtils.isEmpty(token) || null == user) {

  26. // 跳转到登录页面,把用户请求的url作为参数传递给登录页面。

  27. response.sendRedirect("http://localhost:8081/login?redirect=" + request.getRequestURL());

  28. // 返回false

  29. return false;

  30. }

  31. // 把用户信息放入Request

  32. request.setAttribute("user", user);

  33. // 返回值决定handler是否执行。true:执行,false:不执行。

  34. return true;

  35. }

  36.  
  37. @Override

  38. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,

  39. ModelAndView modelAndView) throws Exception {

  40. }

  41.  
  42. @Override

  43. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,

  44. Exception ex) throws Exception {

  45. }

  46. }

可能存在的问题

SpringData 自动更新问题

SpringData 是基于Hibernate的。当User 已经是持久化对象,被保存在session缓存当中。若User又重新修改属性值,在提交事务时,此时hibernate对象就会拿当前这个User对象和保存在session缓存中的User对象进行比较,如果两个对象相同,则不会发送update语句,否则,会发出update语句。 
笔者采用比较傻的方法,就是在提交事务之前把数据还原。各位如果有更好的办法请告知,谢谢! 
参考博客:http://www.cnblogs.com/xiaoluo501395377/p/3380270.html

检查用户信息是否保存

登录成功后,进入Redis客户端查看用户信息是否保存成功。同时为了方便测试,也可以删除这个key。

 
  1. [root@localhost bin]# ./redis-cli -h 192.168.225.131 -p 6379

  2. 192.168.225.131:6379>

  3. 192.168.225.131:6379> keys *

  4. 1) "REDIS_USER_SESSION:1d869ac0-3d22-4e22-bca0-37c8dfade9ad"

  5. 192.168.225.131:6379> get REDIS_USER_SESSION:1d869ac0-3d22-4e22-bca0-37c8dfade9ad

  6. "{\"id\":3,\"account\":\"itdragon\",\"userName\":\"ITDragonGit\",\"plainPassword\":null,\"password\":null,\"salt\":null,\"iphone\":\"12349857999\",\"email\":\"itdragon@git.com\",\"platform\":\"github\",\"createdDate\":\"2017-12-22 21:11:19\",\"updatedDate\":\"2017-12-22 21:11:19\"}"

总结

1 单点登录系统通过将用户信息放在Redis数据库中实现共享Session效果。 
2 Java 配置方式使用四个注解 @Configuration @Bean @PropertySource @Value 。 
3 Spring 拦截器的设置。 
4 HttpClient 的使用 
5 祝大家圣诞节快乐

源码:https://github.com/ITDragonBlog/daydayup/tree/master/SpringBoot/SSO

到这里,基于SpringBoot的单点登录系统就结束了,有什么不对的地方请指出。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值