單點登入系統實現基於SpringBoot

單點登入系統實現基於SpringBoot

今天的乾貨有點溼,裡面夾雜著我的淚水。可能也只有程式碼才能讓我暫時的平靜。透過本章內容你將學到單點登入系統和傳統登入系統的區別,單點登入系統設計思路,Spring4 Java配置方式整合HttpClient,整合SolrJ ,HttpClient簡易教程。還在等什麼?擼起袖子開始幹吧!

效果圖:8081埠是sso系統,其他兩個8082和8083埠模擬兩個系統。登入成功後檢查Redis資料庫中是否有值。

單點登入系統實現基於SpringBoot

web前端免費資源群在下一張圖片下方

技術:SpringBoot,SpringMVC,Spring,SpringData,Redis,HttpClient

說明:本章的使用者登入註冊的程式碼部分已經在SpringBoot基礎入門中介紹過了,這裡不會重複貼程式碼。

原始碼:見文章底部

SpringBoot基礎入門:http://www。cnblogs。com/itdrag。。。

單點登入系統簡介

單點登入系統實現基於SpringBoot

575057881

在傳統的系統,或者是隻有一個伺服器的系統中。Session在一個伺服器中,各個模組都可以直接獲取,只需登入一次就進入各個模組。若在伺服器叢集或者是分散式系統架構中,每個伺服器之間的Session並不是共享的,這會出現每個模組都要登入的情況。這時候需要透過單點登入系統(Single Sign On)將使用者資訊存在Redis資料庫中實現Session共享的效果。從而實現一次登入就可以訪問所有相互信任的應用系統。

單點登入系統實現

Maven專案核心配置檔案 pom。xml 需要在原來的基礎上新增 httpclient和jedis jar包

<!—— http client version is 4。5。3 ——> org。apache。httpcomponents httpclient <!—— redis java client version is 2。9。0 ——> redis。clients jedis

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/d。。。

首先在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配置中的,注意方法名的命名規範

@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配置中的* @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 幫助我們快速開發,但我們也可以自定義配置,這樣可以更方便地掌控。

Redis 系列教程 : http://www。cnblogs。com/itdrag。。。

首先在src/main/resources 目錄下建立 redis。properties 配置檔案

設定Redis主機的ip地址和埠號,和存入Redis資料庫中的key以及存活時間。這裡為了方便測試,存活時間設定的比較小。這裡的配置是單例Redis。

redis。node。host=192。168。225。131redis。node。port=6379REDIS_USER_SESSION_KEY=REDIS_USER_SESSIONSSO_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 jedisShardInfos = new ArrayList(); 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;@Controllerpublic 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> 歡迎登入

Welcome

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 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 param) {// 帶引數post請求 CloseableHttpClient httpClient = HttpClients。createDefault(); // 建立一個預設可關閉的Httpclient 物件 CloseableHttpResponse response = null; String resultMsg = “”; try { HttpPost httpPost = new HttpPost(url); // 建立Http Post請求 if (param != null) { // 建立引數列表 List paramList = new ArrayList(); 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 自定義攔截器

更多web前端免費學習影片qun:575057881

這裡是另外一個專案 itdragon-service-test-sso 中的程式碼,

首先在src/main/resources/spring/springmvc。xml 中配置攔截器,設定那些請求需要攔截

<!—— 攔截器配置 ——>

然後在 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 { }}

可能存在的問題

SpringData 自動更新問題

SpringData 是基於Hibernate的。當User 已經是持久化物件,被儲存在session快取當中。若User又重新修改屬性值,在提交事務時,此時hibernate物件就會拿當前這個User物件和儲存在session快取中的User物件進行比較,如果兩個物件相同,則不會發送update語句,否則,會發出update語句。

筆者採用比較傻的方法,就是在提交事務之前把資料還原。各位如果有更好的辦法請告知,謝謝!

檢查使用者資訊是否儲存

登入成功後,進入Redis客戶端檢視使用者資訊是否儲存成功。同時為了方便測試,也可以刪除這個key。

[root@localhost bin]# 。/redis-cli -h 192。168。225。131 -p 6379192。168。225。131:6379>192。168。225。131:6379> keys *1) “REDIS_USER_SESSION:1d869ac0-3d22-4e22-bca0-37c8dfade9ad”192。168。225。131:6379> get REDIS_USER_SESSION:1d869ac0-3d22-4e22-bca0-37c8dfade9ad“{\”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\“}”