Single sign-on principle and simple implementation

PHPz
Release: 2023-03-06 15:06:02
Original
3805 people have browsed it

1. Single system login mechanism

1. httpNoneStatusProtocol

webApplicationUse browser/ serverArchitecture, http as the communication protocol. http is a stateless protocol. Each request from the browser will be processed independently by the server and will not be associated with previous or subsequent requests. This process is illustrated in the figure below. There is no connection between the three request/response pairs. Any contact

Single sign-on principle and simple implementation But this also means that any user can access server resources through a browser. If you want to protect certain resources on the server, you must limit browser requests; To limit browser requests, you must identify browser requests, respond to legitimate requests, and ignore illegal requests; to identify browser requests, you must know the browser request status. Since the http protocol is stateless, let the server and browser jointly maintain a state! This is the session mechanism

2. Session mechanism

The first time the browser requests the server, the server creates a session and sends the session id to the browser as part of the response. The browser stores Session ID, and bring the session ID in the second and third subsequent requests. The server will know if it is the same user by getting the session ID in the request. This process is illustrated in the figure below. Subsequent requests are the same as the first request. An association is generated

Single sign-on principle and simple implementation The server saves the session

object

in memory. How does the browser save the session id? You may think of two ways

  1. Request parameters

  2. ##cookie
  3. Using the session id as a parameter for each request, the server will naturally parse the parameters to obtain the session id when receiving the request, and use this to determine whether it comes from the same session. Obviously, this method is unreliable. Then let the browser maintain the session ID by itself. The browser automatically sends the session ID every time an http request is sent. The cookie mechanism is used to do this. Cookie is a mechanism used by the browser to store a small amount of data. The data is stored in the form of "
  4. key
/value". When the browser sends an http request, it automatically attaches the cookie information

Of course, the tomcat session mechanism also Cookies are implemented. When accessing the tomcat server, you can see a cookie named "JSESSION

ID" in the browser. This is the session id maintained by the tomcat session mechanism. The request response process using cookies is as shown below.

3. Login status Single sign-on principle and simple implementation

With the session mechanism, the login status is easy to understand. We assume that the browser needs to enter the user name when requesting the server for the first time. Verify the identity with the password. The server gets the user name and password and compares it to the database. If it is correct, it means that the user currently holding this session is a legitimate user. This session should be marked as "authorized" or "logged in", etc. The status, since it is the status of the session, naturally needs to be saved in the session object. Tomcat sets the login status in the session object as follows

HttpSession session = request.getSession();
session.setAttribute("isLogin", true);
Copy after login

When the user visits again, tomcat sets the login status in the session object Check the login status in

HttpSession session = request.getSession();
session.getAttribute("isLogin");
Copy after login

The browser request server that implements the login status
Model

is described in the following figure

Every time a protected resource is requested, the login status in the session object is checked. Only sessions with isLogin=true can be accessed, and the login mechanism is implemented accordingly. Single sign-on principle and simple implementation

2. The complexity of multiple systems

The web system has long developed from a single system in ancient times to an application group composed of multiple systems today. Faced with so many systems, do users have to go one by one? Log in and then log out one by one? Just like the picture below

Single sign-on principle and simple implementation

The web system has developed from a single system to an application group composed of multiple systems. The complexity should be borne by the system itself, not the users. No matter how complex the web system is internally, it is a unified whole for users. That is to say, users accessing the entire application group of the web system is the same as accessing a single system, and only one login/logout is enough

Single sign-on principle and simple implementation

Although the single-system login solution is perfect, it is no longer suitable for multi-system application groups. Why?

The core of the single-system login solution is the cookie. The cookie carries the session ID to maintain the session state between the browser and the server. But there are restrictions on cookies. This restriction is the domain of the cookie (usually corresponding to the domain name of the website). When the browser sends an http request, it will automatically carry cookies that match the domain, not all cookies

Single sign-on principle and simple implementation

In this case, why not unify the domain names of all subsystems in the web application group under one top-level domain name, such as "*.baidu.com", and then set their cookie domains to "baidu.com" , this approach is theoretically possible, and even many early multi-system logins used this method of sharing cookies with the same domain name.

However, feasible does not mean good, and there are many limitations in the way of sharing cookies. First of all, the domain name of the application group must be unified; secondly, the technology used by each system in the application group (at least the web server) must be the same, otherwise the key value of the cookie (JSESSIONID for tomcat) is different, the session cannot be maintained, and the method of sharing cookies cannot be implemented across borders. Language technology platform login, such as java, php, .net system; third, the cookie itself is not safe.

Therefore, we need a new login method to realize the login of multi-system application groups, which is single sign-on

3. Single sign-on

What is single sign-on Click to log in? The full name of single sign-on is Single Sign On (hereinafter referred to as SSO). It means that if you log in to one system in a multi-system application group, you can be authorized in all other systems without logging in again, including single sign on and single logout.

1. Login

Compared with single system login, SSO requires an independent authentication center. Only the authentication center can accept the user's user name, password and other security information. Other systems do not provide login entrances. Only indirect authorization from the certification center is accepted. Indirect authorization is implemented through tokens. The SSO authentication center verifies that the user's username and password are OK, and creates an authorization token. In the next jump process, the authorization token is sent as a parameter to each subsystem, and the subsystem gets the token. , that is, you are authorized to create a partial session. The partial session login method is the same as the single-system login method. This process, which is the principle of single sign-on, is illustrated by the following figure

The following is a brief description of the above figure

  1. user Access the protected resources of system 1. System 1 finds that the user is not logged in, jumps to the sso authentication center, and uses his address as a parameter

  2. sso authentication center finds that the user is not logged in, and will The user is directed to the login page

  3. The user enters the username and password to submit the login application

  4. sso certification center verifies user information, creates users and sso authentication The session between centers is called a global session, and an authorization token is created at the same time.

  5. The sso authentication center will jump to the original request address (system 1) with the token

  6. System 1 gets the token and goes to the sso certification center to verify whether the token is valid

  7. The sso certification center verifies the token, returns valid, and registers the system 1

  8. System 1 uses this token to create a session with the user, called a partial session, returning the protected resource

  9. User accesses System 2 Protected resources

  10. System 2 finds that the user is not logged in, jumps to the sso authentication center, and uses his own address as a parameter

  11. sso The authentication center finds that the user has logged in, jumps back to the address of system 2, and attaches the token

  12. System 2 gets the token and goes to the sso authentication center to verify whether the token is valid

  13. sso authentication center verifies the token and returns valid, registering system 2

  14. System 2 uses the token to create a partial session with the user, Return protected resources

  用户登录成功之后,会与sso认证中心及各个子系统建立会话,用户与sso认证中心建立的会话称为全局会话,用户与各个子系统建立的会话称为局部会话,局部会话建立之后,用户访问子系统受保护资源将不再通过sso认证中心,全局会话与局部会话有如下约束关系

  1. 局部会话存在,全局会话一定存在

  2. 全局会话存在,局部会话不一定存在

  3. 全局会话销毁,局部会话必须销毁

  你可以通过博客园、百度、csdn、淘宝等网站的登录过程加深对单点登录的理解,注意观察登录过程中的跳转url与参数

2、注销

  单点登录自然也要单点注销,在一个子系统中注销,所有子系统的会话都将被销毁,用下面的图来说明

Single sign-on principle and simple implementation

  sso认证中心一直监听全局会话的状态,一旦全局会话销毁,监听器将通知所有注册系统执行注销操作

  下面对上图简要说明

  1. 用户向系统1发起注销请求

  2. 系统1根据用户与系统1建立的会话id拿到令牌,向sso认证中心发起注销请求

  3. sso认证中心校验令牌有效,销毁全局会话,同时取出所有用此令牌注册的系统地址

  4. sso认证中心向所有注册系统发起注销请求

  5. 各注册系统接收sso认证中心的注销请求,销毁局部会话

  6. sso认证中心引导用户至登录页面

四、部署图

  单点登录涉及sso认证中心与众子系统,子系统与sso认证中心需要通信以交换令牌、校验令牌及发起注销请求,因而子系统必须集成sso的客户端,sso认证中心则是sso服务端,整个单点登录过程实质是sso客户端与服务端通信的过程,用下图描述

Single sign-on principle and simple implementation

  sso认证中心与sso客户端通信方式有多种,这里以简单好用的httpClient为例,web service、rpc、restful api都可以

五、实现

  只是简要介绍下基于java的实现过程,不提供完整源码,明白了原理,我相信你们可以自己实现。sso采用客户端/服务端架构,我们先看sso-client与sso-server要实现的功能(下面:sso认证中心=sso-server)

  sso-client

  1. 拦截子系统未登录用户请求,跳转至sso认证中心

  2. 接收并存储sso认证中心发送的令牌

  3. 与sso-server通信,校验令牌的有效性

  4. 建立局部会话

  5. 拦截用户注销请求,向sso认证中心发送注销请求

  6. 接收sso认证中心发出的注销请求,销毁局部会话

  sso-server

  1. 验证用户的登录信息

  2. 创建全局会话

  3. 创建授权令牌

  4. 与sso-client通信发送令牌

  5. 校验sso-client令牌有效性

  6. 系统注册

  7. 接收sso-client注销请求,注销所有会话

  接下来,我们按照原理来一步步实现sso吧!

1、sso-client拦截未登录请求

  java拦截请求的方式有servlet、filter、listener三种方式,我们采用filter。在sso-client中新建LoginFilter.java类并实现Filter接口,在doFilter()方法中加入对未登录用户的拦截


public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = req.getSession();
    if (session.getAttribute("isLogin")) {
        chain.doFilter(request, response);
        return;
    }
    //跳转至sso认证中心
    res.sendRedirect("sso-server-url-with-system-url");
}
Copy after login

2、sso-server拦截未登录请求

  拦截从sso-client跳转至sso认证中心的未登录请求,跳转至登录页面,这个过程与sso-client完全一样

3、sso-server验证用户登录信息

  用户在登录页面输入用户名密码,请求登录,sso认证中心校验用户信息,校验成功,将会话状态标记为“已登录”


@RequestMapping("/login")
public String login(String username, String password, HttpServletRequest req) {
    this.checkLoginInfo(username, password);
    req.getSession().setAttribute("isLogin", true);
    return "success";
}
Copy after login

4、sso-server创建授权令牌

  授权令牌是一串随机字符,以什么样的方式生成都没有关系,只要不重复、不易伪造即可,下面是一个例子


String token = UUID.randomUUID().toString();
Copy after login

5、sso-client取得令牌并校验

  sso认证中心登录后,跳转回子系统并附上令牌,子系统(sso-client)取得令牌,然后去sso认证中心校验,在LoginFilter.java的doFilter()中添加几行


// 请求附带token参数
String token = req.getParameter("token");
if (token != null) {
    // 去sso认证中心校验token
    boolean verifyResult = this.verify("sso-server-verify-url", token);
    if (!verifyResult) {
        res.sendRedirect("sso-server-url");
        return;
    }
    chain.doFilter(request, response);
}
Copy after login

  verify()方法使用httpClient实现,这里仅简略介绍,httpClient详细使用方法请参考官方文档


HttpPost httpPost = new HttpPost("sso-server-verify-url-with-token");
HttpResponse httpResponse = httpClient.execute(httpPost);
Copy after login

6、sso-server接收并处理校验令牌请求

  用户在sso认证中心登录成功后,sso-server创建授权令牌并存储该令牌,所以,sso-server对令牌的校验就是去查找这个令牌是否存在以及是否过期,令牌校验成功后sso-server将发送校验请求的系统注册到sso认证中心(就是存储起来的意思)

  令牌与注册系统地址通常存储在key-value数据库(如redis)中,redis可以为key设置有效时间也就是令牌的有效期。redis运行在内存中,速度非常快,正好sso-server不需要持久化任何数据。

  令牌与注册系统地址可以用下图描述的结构存储在redis中,可能你会问,为什么要存储这些系统的地址?如果不存储,注销的时候就麻烦了,用户向sso认证中心提交注销请求,sso认证中心注销全局会话,但不知道哪些系统用此全局会话建立了自己的局部会话,也不知道要向哪些子系统发送注销请求注销局部会话

Single sign-on principle and simple implementation

7、sso-client校验令牌成功创建局部会话

  令牌校验成功后,sso-client将当前局部会话标记为“已登录”,修改LoginFilter.java,添加几行


if (verifyResult) {
    session.setAttribute("isLogin", true);
}
Copy after login

  sso-client还需将当前会话id与令牌绑定,表示这个会话的登录状态与令牌相关,此关系可以用java的hashmap保存,保存的数据用来处理sso认证中心发来的注销请求

8、注销过程

  用户向子系统发送带有“logout”参数的请求(注销请求),sso-client拦截器拦截该请求,向sso认证中心发起注销请求


String logout = req.getParameter("logout");
if (logout != null) {
    this.ssoServer.logout(token);
}
Copy after login

  sso认证中心也用同样的方式识别出sso-client的请求是注销请求(带有“logout”参数),sso认证中心注销全局会话


@RequestMapping("/logout")
public String logout(HttpServletRequest req) {
    HttpSession session = req.getSession();
    if (session != null) {
        session.invalidate();//触发LogoutListener
    }
    return "redirect:/";
}
Copy after login

  sso认证中心有一个全局会话的监听器,一旦全局会话注销,将通知所有注册系统注销


public class LogoutListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent event) {}
    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        //通过httpClient向所有注册系统发送注销请求
    }
}
Copy after login

The above is the detailed content of Single sign-on principle and simple implementation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template