單點登錄系統實現
Maven項目核心配置文件 pom.xml 需要在原來的基礎上添加 httpclient和jedis jar包
<dependency> <!-- http client version is 4.5.3 --> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <!-- redis java client version is 2.9.0 --> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </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 協議最新的版本和建議。
首先在src/main/resources 目錄下創建 httpclient.properties 配置文件
#設置整個連接池默認最大連接數
http.defaultMaxPerRoute=100
#設置整個連接池最大連接數
http.maxTotal=300
#設置請求超時
http.connectTimeout=1000
#設置從連接池中獲取到連接的最長時間
http.connectionRequestTimeout=500
#設置數據傳輸的最長時間
http.socketTimeout=10000
然后在 src/main/java/com/itdragon/config 目錄下創建 HttpclientSpringConfig.java 文件
這里用到了四個很重要的注解
@Configuration : 作用於類上,指明該類就相當於一個xml配置文件
@Bean : 作用於方法上,指明該方法相當於xml配置中的<bean>,注意方法名的命名規范
@PropertySource : 指定讀取的配置文件,引入多個value={"xxx:xxx","xxx:xxx"},ignoreResourceNotFound=true 文件不存在是忽略
@Value : 獲取配置文件的值,該注解還有很多語法知識,這里暫時不擴展開
package com.itdragon.config; import java.util.concurrent.TimeUnit; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.IdleConnectionEvictor; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.Scope; /** * @Configuration 作用於類上,相當於一個xml配置文件 * @Bean 作用於方法上,相當於xml配置中的<bean> * @PropertySource 指定讀取的配置文件 * @Value 獲取配置文件的值 */ @Configuration @PropertySource(value = "classpath:httpclient.properties") public class HttpclientSpringConfig { @Value("${http.maxTotal}") private Integer httpMaxTotal; @Value("${http.defaultMaxPerRoute}") private Integer httpDefaultMaxPerRoute; @Value("${http.connectTimeout}") private Integer httpConnectTimeout; @Value("${http.connectionRequestTimeout}") private Integer httpConnectionRequestTimeout; @Value("${http.socketTimeout}") private Integer httpSocketTimeout; @Autowired private PoolingHttpClientConnectionManager manager; @Bean public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() { PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); // 最大連接數 poolingHttpClientConnectionManager.setMaxTotal(httpMaxTotal); // 每個主機的最大並發數 poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpDefaultMaxPerRoute); return poolingHttpClientConnectionManager; } @Bean // 定期清理無效連接 public IdleConnectionEvictor idleConnectionEvictor() { return new IdleConnectionEvictor(manager, 1L, TimeUnit.HOURS); } @Bean // 定義HttpClient對象 注意該對象需要設置scope="prototype":多例對象 @Scope("prototype") public CloseableHttpClient closeableHttpClient() { return HttpClients.custom().setConnectionManager(this.manager).build(); } @Bean // 請求配置 public RequestConfig requestConfig() { return RequestConfig.custom().setConnectTimeout(httpConnectTimeout) // 創建連接的最長時間 .setConnectionRequestTimeout(httpConnectionRequestTimeout) // 從連接池中獲取到連接的最長時間 .setSocketTimeout(httpSocketTimeout) // 數據傳輸的最長時間 .build(); } }
整合 Redis
SpringBoot官方其實提供了spring-boot-starter-redis pom 幫助我們快速開發,但我們也可以自定義配置,這樣可以更方便地掌控。
首先在src/main/resources 目錄下創建 redis.properties 配置文件
設置Redis主機的ip地址和端口號,和存入Redis數據庫中的key以及存活時間。這里為了方便測試,存活時間設置的比較小。這里的配置是單例Redis。
redis.node.host=127.0.0.1 redis.node.port=6379 REDIS_USER_SESSION_KEY=REDIS_USER_SESSION SSO_SESSION_EXPIRE=30
在src/main/java/com/itdragon/config 目錄下創建 RedisSpringConfig.java 文件
package com.itdragon.config; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedisPool; @Configuration @PropertySource(value = "classpath:redis.properties") public class RedisSpringConfig { @Value("${redis.maxTotal}") private Integer redisMaxTotal; @Value("${redis.node.host}") private String redisNodeHost; @Value("${redis.node.port}") private Integer redisNodePort; private JedisPoolConfig jedisPoolConfig() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(redisMaxTotal); return jedisPoolConfig; } @Bean public JedisPool getJedisPool(){ // 省略第一個參數則是采用 Protocol.DEFAULT_DATABASE JedisPool jedisPool = new JedisPool(jedisPoolConfig(), redisNodeHost, redisNodePort); return jedisPool; } @Bean public ShardedJedisPool shardedJedisPool() { List<JedisShardInfo> jedisShardInfos = new ArrayList<JedisShardInfo>(); jedisShardInfos.add(new JedisShardInfo(redisNodeHost, redisNodePort)); return new ShardedJedisPool(jedisPoolConfig(), jedisShardInfos); } }
Service 層
在src/main/java/com/itdragon/service 目錄下創建 UserService.java 文件,它負責三件事情
第一件事件:驗證用戶信息是否正確,並將登錄成功的用戶信息保存到Redis數據庫中。
第二件事件:負責判斷用戶令牌是否過期,若沒有則刷新令牌存活時間。
第三件事件:負責從Redis數據庫中刪除用戶信息。
這里用到了一些工具類,不影響學習,可以從源碼中直接獲取。
package com.itdragon.service; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.itdragon.pojo.ItdragonResult; import com.itdragon.pojo.User; import com.itdragon.repository.JedisClient; import com.itdragon.repository.UserRepository; import com.itdragon.utils.CookieUtils; import com.itdragon.utils.ItdragonUtils; import com.itdragon.utils.JsonUtils; @Service @Transactional @PropertySource(value = "classpath:redis.properties") public class UserService { @Autowired private UserRepository userRepository; @Autowired private JedisClient jedisClient; @Value("${REDIS_USER_SESSION_KEY}") private String REDIS_USER_SESSION_KEY; @Value("${SSO_SESSION_EXPIRE}") private Integer SSO_SESSION_EXPIRE; public ItdragonResult userLogin(String account, String password, HttpServletRequest request, HttpServletResponse response) { // 判斷賬號密碼是否正確 User user = userRepository.findByAccount(account); if (!ItdragonUtils.decryptPassword(user, password)) { return ItdragonResult.build(400, "賬號名或密碼錯誤"); } // 生成token String token = UUID.randomUUID().toString(); // 清空密碼和鹽避免泄漏 String userPassword = user.getPassword(); String userSalt = user.getSalt(); user.setPassword(null); user.setSalt(null); // 把用戶信息寫入 redis jedisClient.set(REDIS_USER_SESSION_KEY + ":" + token, JsonUtils.objectToJson(user)); // user 已經是持久化對象,被保存在session緩存當中,若user又重新修改屬性值,那么在提交事務時,此時 hibernate對象就會拿當前這個user對象和保存在session緩存中的user對象進行比較,如果兩個對象相同,則不會發送update語句,否則會發出update語句。 user.setPassword(userPassword); user.setSalt(userSalt); // 設置 session 的過期時間 jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE); // 添加寫 cookie 的邏輯,cookie 的有效期是關閉瀏覽器就失效。 CookieUtils.setCookie(request, response, "USER_TOKEN", token); // 返回token return ItdragonResult.ok(token); } public void logout(String token) { jedisClient.del(REDIS_USER_SESSION_KEY + ":" + token); } public ItdragonResult queryUserByToken(String token) { // 根據token從redis中查詢用戶信息 String json = jedisClient.get(REDIS_USER_SESSION_KEY + ":" + token); // 判斷是否為空 if (StringUtils.isEmpty(json)) { return ItdragonResult.build(400, "此session已經過期,請重新登錄"); } // 更新過期時間 jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE); // 返回用戶信息 return ItdragonResult.ok(JsonUtils.jsonToPojo(json, User.class)); } }
Controller 層
負責跳轉登錄頁面跳轉
package com.itdragon.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class PageController { @RequestMapping("/login") public String showLogin(String redirect, Model model) { model.addAttribute("redirect", redirect); return "login"; } }
負責用戶的登錄,退出,獲取令牌的操作
package com.itdragon.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.itdragon.pojo.ItdragonResult; import com.itdragon.service.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value="/login", method=RequestMethod.POST) @ResponseBody public ItdragonResult userLogin(String username, String password, HttpServletRequest request, HttpServletResponse response) { try { ItdragonResult result = userService.userLogin(username, password, request, response); return result; } catch (Exception e) { e.printStackTrace(); return ItdragonResult.build(500, ""); } } @RequestMapping(value="/logout/{token}") public String logout(@PathVariable String token) { userService.logout(token); // 思路是從Redis中刪除key,實際情況請和業務邏輯結合 return "index"; } @RequestMapping("/token/{token}") @ResponseBody public Object getUserByToken(@PathVariable String token) { ItdragonResult result = null; try { result = userService.queryUserByToken(token); } catch (Exception e) { e.printStackTrace(); result = ItdragonResult.build(500, ""); } return result; } }
視圖層
一個簡單的登錄頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!doctype html> <html lang="zh"> <head> <meta name="viewport" content="initial-scale=1.0, width=device-width, user-scalable=no" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1" /> <meta http-equiv="X-UA-Compatible" content="IE=8" /> <title>歡迎登錄</title> <link type="image/x-icon" href="images/favicon.ico" rel="shortcut icon"> <link rel="stylesheet" href="static/css/main.css" /> </head> <body> <div class="wrapper"> <div class="container"> <h1>Welcome</h1> <form method="post" onsubmit="return false;" class="form"> <input type="text" value="itdragon" name="username" placeholder="Account"/> <input type="password" value="123456789" name="password" placeholder="Password"/> <button type="button" id="login-button">Login</button> </form> </div> <ul class="bg-bubbles"> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> <script type="text/javascript" src="static/js/jquery-1.10.1.min.js" ></script> <script type="text/javascript"> var redirectUrl = "${redirect}"; // 瀏覽器中返回的URL function doLogin() { $.post("/user/login", $(".form").serialize(),function(data){ if (data.status == 200) { if (redirectUrl == "") { location.href = "http://localhost:8082"; } else { location.href = redirectUrl; } } else { alert("登錄失敗,原因是:" + data.msg); } }); } $(function(){ $("#login-button").click(function(){ doLogin(); }); }); </script> </body> </html>
HttpClient 基礎語法
這里封裝了get,post請求的方法
package com.itdragon.utils; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpClientUtil { public static String doGet(String url) { // 無參數get請求 return doGet(url, null); } public static String doGet(String url, Map<String, String> param) { // 帶參數get請求 CloseableHttpClient httpClient = HttpClients.createDefault(); // 創建一個默認可關閉的Httpclient 對象 String resultMsg = ""; // 設置返回值 CloseableHttpResponse response = null; // 定義HttpResponse 對象 try { URIBuilder builder = new URIBuilder(url); // 創建URI,可以設置host,設置參數等 if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); HttpGet httpGet = new HttpGet(uri); // 創建http GET請求 response = httpClient.execute(httpGet); // 執行請求 if (response.getStatusLine().getStatusCode() == 200) { // 判斷返回狀態為200則給返回值賦值 resultMsg = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { // 不要忘記關閉 try { if (response != null) { response.close(); } httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultMsg; } public static String doPost(String url) { // 無參數post請求 return doPost(url, null); } public static String doPost(String url, Map<String, String> param) {// 帶參數post請求 CloseableHttpClient httpClient = HttpClients.createDefault(); // 創建一個默認可關閉的Httpclient 對象 CloseableHttpResponse response = null; String resultMsg = ""; try { HttpPost httpPost = new HttpPost(url); // 創建Http Post請求 if (param != null) { // 創建參數列表 List<NameValuePair> paramList = new ArrayList<NameValuePair>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);// 模擬表單 httpPost.setEntity(entity); } response = httpClient.execute(httpPost); // 執行http請求 if (response.getStatusLine().getStatusCode() == 200) { resultMsg = EntityUtils.toString(response.getEntity(), "utf-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultMsg; } public static String doPostJson(String url, String json) { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } }
Spring 自定義攔截器
這里是另外一個項目 itdragon-service-test-sso 中的代碼,
首先在src/main/resources/spring/springmvc.xml 中配置攔截器,設置那些請求需要攔截
<!-- 攔截器配置 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/github/**"/> <bean class="com.itdragon.interceptors.UserLoginHandlerInterceptor"/> </mvc:interceptor> </mvc:interceptors>
然后在 src/main/java/com/itdragon/interceptors 目錄下創建 UserLoginHandlerInterceptor.java 文件
package com.itdragon.interceptors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.itdragon.pojo.User; import com.itdragon.service.UserService; import com.itdragon.utils.CookieUtils; public class UserLoginHandlerInterceptor implements HandlerInterceptor { public static final String COOKIE_NAME = "USER_TOKEN"; @Autowired private UserService userService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = CookieUtils.getCookieValue(request, COOKIE_NAME); User user = this.userService.getUserByToken(token); if (StringUtils.isEmpty(token) || null == user) { // 跳轉到登錄頁面,把用戶請求的url作為參數傳遞給登錄頁面。 response.sendRedirect("http://localhost:8081/login?redirect=" + request.getRequestURL()); // 返回false return false; } // 把用戶信息放入Request request.setAttribute("user", user); // 返回值決定handler是否執行。true:執行,false:不執行。 return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
以上是一個單點登錄的實現示例
-------------------------額外補充-----------------------------------------
題主在附帶中還說明了幾個訴求:
第一個訴求 :需要跨域登錄
這個實現有兩種方案
方案1:一種是基於cas的重定向到單點登錄服務器認證后返回ticket來實現,詳細流程如下:

- 用戶訪問app系統,app系統是需要登錄的,但用戶現在沒有登錄。
- 跳轉到CAS server,即SSO登錄系統,以后圖中的CAS Server我們統一叫做SSO系統。 SSO系統也沒有登錄,彈出用戶登錄頁。
- 用戶填寫用戶名、密碼,SSO系統進行認證后,將登錄狀態寫入SSO的session,瀏覽器(Browser)中寫入SSO域下的Cookie。
- SSO系統登錄完成后會生成一個ST(Service Ticket),然后跳轉到app系統,同時將ST作為參數傳遞給app系統。
- app系統拿到ST后,從后台向SSO發送請求,驗證ST是否有效。
- 驗證通過后,app系統將登錄狀態寫入session並設置app域下的Cookie。
至此,跨域單點登錄就完成了。以后我們再訪問app系統時,app就是登錄的。接下來,我們再看看訪問app2系統時的流程。
- 用戶訪問app2系統,app2系統沒有登錄,跳轉到SSO。
- 由於SSO已經登錄了,不需要重新登錄認證。
- SSO生成ST,瀏覽器跳轉到app2系統,並將ST作為參數傳遞給app2。
- app2拿到ST,后台訪問SSO,驗證ST是否有效。
- 驗證成功后,app2將登錄狀態寫入session,並在app2域下寫入Cookie。
這樣,app2系統不需要走登錄流程,就已經是登錄了。SSO,app和app2在不同的域,它們之間的session不共享也是沒問題的。
方案1的缺點在於所有的app都需要返回到sso服務器進行登錄校驗,會大大用戶訪問時延,並且sso服務器壓力會增大。
方案2:采用多域名集合方式,寫入各個域名的cookie
具體流程如下:
1、用戶在A域名首先登錄,發現沒有session,定向到sso服務器
2、sso服務器登錄驗證完成
3、sso服務器具有多域名解析(例如login.a.com;http://login.b.com),重定向到這些域名下帶上cookie的key和value,再返回頁面端寫入對應cookie
4、a域名用戶登錄返回
5、同一個用戶訪問b域名,域名下已有cookie,到b域名服務器下的filter自動提取cookie到sso服務器(api或者rpc接口)獲取對應的用戶信息,構建session,實現自動登錄,無需再二次登錄
第二個訴求 :開源項目
典型的就是cas,git地址如下:https://github.com/apereo/cas