公司系統太多,能不能實現賬號互通?
背景
最近開發新產品,然后老板說我們現在系統太多了,每次切換系統登錄太麻煩了,能不能做個優化,同一賬號互通掉。作為一個資深架構獅,老板的要求肯定要滿足,安排!
一個公司產品矩陣比較豐富的時候,用戶在不同系統之間來回切換,固然對產品用戶體驗上較差,并且增加用戶密碼管理成本。
也沒有很好地利用內部流量進行用戶打通,并且每個產品的獨立體系會導致產品安全度下降。
因此實現集團產品的單點登錄對用戶使用體驗以及效率提升有很大的幫助。那么如何實現統一認證呢?我們先了解一下傳統的身份驗證方式。
傳統 Session 機制及身份認證方案
Cookie 與服務器的交互
眾所周知,http 是無狀態的協議,因此客戶每次通過瀏覽器訪問 web。
頁面,請求到服務端時,服務器都會新建線程,打開新的會話,而且服務器也不會自動維護客戶的上下文信息。
比如我們現在要實現一個電商內的購物車功能,要怎么才能知道哪些購物車請求對應的是來自同一個客戶的請求呢?
因此出現了 session 這個概念,session 就是一種保存上下文信息的機制,他是面向用戶的,每一個 SessionID 對應著一個用戶,并且保存在服務端中。
session 主要以 cookie 或 URL 重寫為基礎的來實現的,默認使用 cookie 來實現,系統會創造一個名為 JSESSIONID 的變量輸出到 cookie 中。
JSESSIONID 是存儲于瀏覽器內存中的,并不是寫到硬盤上的,如果我們把瀏覽器的cookie 禁止,則 web 服務器會采用 URL 重寫的方式傳遞 Sessionid,我們就可以在地址欄看到 sessinotallow=KWJHUG6JJM65HS2K6 之類的字符串。
通常 JSESSIONID 是不能跨窗口使用的,當你新開了一個瀏覽器窗口進入相同頁面時,系統會賦予你一個新的 sessionid,這樣我們信息共享的目的就達不到了。
服務器端的 session 的機制
當服務端收到客戶端的請求時候,首先判斷請求里是否包含了 JSESSIONID 的 sessionId,如果存在說明已經創建過了,直接從內存中拿出來使用,如果查詢不到,說明是無效的。
如果客戶請求不包含 sessionid,則為此客戶創建一個 session 并且生成一個與此 session 相關聯的 sessionid,這個 sessionid 將在本次響應中返回給客戶端保存。
對每次 http 請求,都經歷以下步驟處理:
- 服務端首先查找對應的 cookie 的值(sessionid)。
- 根據 sessionid,從服務器端 session 存儲中獲取對應 id 的 session 數據,進行返回。
- 如果找不到 sessionid,服務器端就創建 session,生成 sessionid 對應的 cookie,寫入到響應頭中。
session 是由服務端生成的,并且以散列表的形式保存在內存中。
基于 session 的身份認證流程
基于 seesion 的身份認證主要流程如下:
圖片
因為 http 請求是無狀態請求,所以在 Web 領域,大部分都是通過這種方式解決。但是這么做有什么問題呢?我們接著看。
集群環境下的 Session 困境及解決方案
隨著技術的發展,用戶流量增大,單個服務器已經不能滿足系統的需要了,分布式架構開始流行。
圖片
通常都會把系統部署在多臺服務器上,通過負載均衡把請求分發到其中的一臺服務器上,這樣很可能同一個用戶的請求被分發到不同的服務器上。
因為 session 是保存在服務器上的,那么很有可能第一次請求訪問的 A 服務器,創建了 session,但是第二次訪問到了 B 服務器,這時就會出現取不到 session 的情況。
我們知道,Session 一般是用來存會話全局的用戶信息(不僅僅是登陸方面的問題),用來簡化/加速后續的業務請求。
傳統的 session 由服務器端生成并存儲,當應用進行分布式集群部署的時候,如何保證不同服務器上 session 信息能夠共享呢?
Session 共享方案
Session 共享一般有兩種思路:
- session 復制
- session 集中存儲
①session 復制
session 復制即將不同服務器上 session 數據進行復制,用戶登錄,修改,注銷時,將 session 信息同時也復制到其他機器上面去。
圖片
這種實現的問題就是實現成本高,維護難度大,并且會存在延遲登問題。
②session 集中存儲
圖片
集中存儲就是將獲取 session 單獨放在一個服務中進行存儲,所有獲取 session 的統一來這個服務中去取。
這樣就避免了同步和維護多套 session 的問題。一般我們都是使用 redis 進行集中式存儲 session。
多服務下的登陸困境及 SSO 方案
SSO 的產生背景
圖片
如果企業做大了之后,一般都有很多的業務支持系統為其提供相應的管理和 IT 服務,按照傳統的驗證方式訪問多系統,每個單獨的系統都會有自己的安全體系和身份認證系統。
進入每個系統都需要進行登錄,獲取 session,再通過 session 訪問對應系統資源。
這樣的局面不僅給管理上帶來了很大的困難,對客戶來說也極不友好,那么如何讓客戶只需登陸一次,就可以進入多個系統,而不需要重新登錄呢?
圖片
“單點登錄”就是專為解決此類問題的。其大致思想流程如下:通過一個 ticket 進行串接各系統間的用戶信息。
SSO 的底層原理 CAS
①CAS 實現單點登錄流程
我們知道對于完全不同域名的系統,cookie 是無法跨域名共享的,因此 sessionId 在頁面端也無法共享,因此需要實現單店登錄,就需要啟用一個專門用來登錄的域名如(ouath.com)來提供所有系統的 sessionId。
當業務系統被打開時,借助中心授權系統進行登錄,整體流程如下:
- 當 b.com 打開時,發現自己未登陸,于是跳轉到 ouath.com 去登陸
- ouath.com 登陸頁面被打開,用戶輸入帳戶/密碼登陸成功
- ouath.com 登陸成功,種 cookie 到 ouath.com 域名下
- 把 sessionid 放入后臺 redis,存放<ticket,sesssionid>數據結構,然后頁面重定向到 A 系統
- 當 b.com 重新被打開,發現仍然是未登陸,但是有了一個 ticket 值
- 當 b.com 用 ticket 值,到 redis 里查到 sessionid,并做 session 同步,然后種 cookie 給自己,頁面原地重定向
- 當 b.com 打開自己頁面,此時有了 cookie,后臺校驗登陸狀態,成功
整個交互流程圖如下:
圖片
②單點登錄流程演示
用戶實體類:
public class UserForm implements Serializable{
privatestaticfinallong serialVersionUID = 1L;
private String username;
private String password;
private String backurl;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getBackurl() {
return backurl;
}
public void setBackurl(String backurl) {
this.backurl = backurl;
}
}
登錄控制器:
@Controller
publicclass IndexController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping("/toLogin")
public String toLogin(Model model,HttpServletRequest request) {
Object userInfo = request.getSession().getAttribute(LoginFilter.USER_INFO);
//不為空,則是已登陸狀態
if (null != userInfo){
String ticket = UUID.randomUUID().toString();
redisTemplate.opsForValue().set(ticket,userInfo,2, TimeUnit.SECONDS);
return"redirect:"+request.getParameter("url")+"?ticket="+ticket;
}
UserForm user = new UserForm();
user.setUsername("laowang");
user.setPassword("laowang");
user.setBackurl(request.getParameter("url"));
model.addAttribute("user", user);
return"login";
}
@PostMapping("/login")
public void login(@ModelAttribute UserForm user,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
System.out.println("backurl:"+user.getBackurl());
request.getSession().setAttribute(LoginFilter.USER_INFO,user);
//登陸成功,創建用戶信息票據
String ticket = UUID.randomUUID().toString();
redisTemplate.opsForValue().set(ticket,user,20, TimeUnit.SECONDS);
//重定向,回原url ---a.com
if (null == user.getBackurl() || user.getBackurl().length()==0){
response.sendRedirect("/index");
} else {
response.sendRedirect(user.getBackurl()+"?ticket="+ticket);
}
}
@GetMapping("/index")
public ModelAndView index(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView();
Object user = request.getSession().getAttribute(LoginFilter.USER_INFO);
UserForm userInfo = (UserForm) user;
modelAndView.setViewName("index");
modelAndView.addObject("user", userInfo);
request.getSession().setAttribute("test","123");
return modelAndView;
}
}
登錄過濾器:
public class LoginFilter implements Filter {
publicstaticfinal String USER_INFO = "user";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
Object userInfo = request.getSession().getAttribute(USER_INFO);;
//如果未登陸,則拒絕請求,轉向登陸頁面
String requestUrl = request.getServletPath();
if (!"/toLogin".equals(requestUrl)//不是登陸頁面
&& !requestUrl.startsWith("/login")//不是去登陸
&& null == userInfo) {//不是登陸狀態
request.getRequestDispatcher("/toLogin").forward(request,response);
return ;
}
filterChain.doFilter(request,servletResponse);
}
@Override
public void destroy() {
}
}
配置過濾器:
@Configuration
publicclass LoginConfig {
//配置filter生效
@Bean
public FilterRegistrationBean sessionFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new LoginFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("sessionFilter");
registration.setOrder(1);
return registration;
}
}
登錄頁面:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>enjoy login</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div text-align="center">
<h1>請登陸</h1>
<form action="#" th:action="@{/login}" th:object="${user}" method="post">
<p>用戶名: <input type="text" th:field="*{username}" /></p>
<p>密 碼: <input type="text" th:field="*{password}" /></p>
<p><input type="submit" value="Submit" /><input type="reset" value="Reset" /></p>
<input type="text" th:field="*{backurl}" hidden="hidden" />
</form>
</div>
</body>
</html>
過濾器:
public class SSOFilter implements Filter {
private RedisTemplate redisTemplate;
publicstaticfinal String USER_INFO = "user";
public SSOFilter(RedisTemplate redisTemplate){
this.redisTemplate = redisTemplate;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
Object userInfo = request.getSession().getAttribute(USER_INFO);;
//如果未登陸,則拒絕請求,轉向登陸頁面
String requestUrl = request.getServletPath();
if (!"/toLogin".equals(requestUrl)//不是登陸頁面
&& !requestUrl.startsWith("/login")//不是去登陸
&& null == userInfo) {//不是登陸狀態
String ticket = request.getParameter("ticket");
//有票據,則使用票據去嘗試拿取用戶信息
if (null != ticket){
userInfo = redisTemplate.opsForValue().get(ticket);
}
//無法得到用戶信息,則去登陸頁面
if (null == userInfo){
response.sendRedirect("http://127.0.0.1:8080/toLogin?url="+request.getRequestURL().toString());
return ;
}
/**
* 將用戶信息,加載進session中
*/
UserForm user = (UserForm) userInfo;
request.getSession().setAttribute(SSOFilter.USER_INFO,user);
redisTemplate.delete(ticket);
}
filterChain.doFilter(request,servletResponse);
}
@Override
public void destroy() {
}
}
控制器:
@Controller
publicclass IndexController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping("/index")
public ModelAndView index(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView();
Object userInfo = request.getSession().getAttribute(SSOFilter.USER_INFO);
UserForm user = (UserForm) userInfo;
modelAndView.setViewName("index");
modelAndView.addObject("user", user);
request.getSession().setAttribute("test","123");
return modelAndView;
}
}
首頁:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>enjoy index</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div th:object="${user}">
<h1>cas-website:歡迎你"></h1>
</div>
</body>
</html>
③CAS 的單點登錄和 OAuth2 的區別
OAuth2:三方授權協議,允許用戶在不提供賬號密碼的情況下,通過信任的應用進行授權,使其客戶端可以訪問權限范圍內的資源。
CAS:中央認證服務(Central Authentication Service),一個基于 Kerberos 票據方式實現 SSO 單點登錄的框架,為 Web 應用系統提供一種可靠的單點登錄解決方法(屬于 Web SSO )。
CAS 的單點登錄時保障客戶端的用戶資源的安全 ;OAuth2 則是保障服務端的用戶資源的安全 。
CAS 客戶端要獲取的最終信息是,這個用戶到底有沒有權限訪問我(CAS 客戶端)的資源;OAuth2 獲取的最終信息是,我(oauth2 服務提供方)的用戶的資源到底能不能讓你(oauth2 的客戶端)訪問。
因此,需要統一的賬號密碼進行身份認證,用 CAS;需要授權第三方服務使用我方資源,使用 OAuth2。