Home>Article>Backend Development> Examples to explain the principle of SSO single sign-on
1. http stateless protocol
The web application adopts browser/server architecture, and http is used 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
But this also means that any user can access server resources through a browser. If you want to protect certain resources of 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
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
# The server saves the session object in memory, how does the browser save the session id? You may think of two ways
Request parameters
cookie
# Use the session id as For each request parameter, when the server receives the request, it can naturally parse the parameters to obtain the session ID, 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 "key/value". When the browser sends an http request, it automatically attaches cookie information
Of course, the tomcat session mechanism also implements cookies. Visit tomcat When running the server, you can see a cookie named "JSESSIONID" in the browser. This is the session ID maintained by the tomcat session mechanism. The request response process using cookies is as shown below
With the session mechanism, the login status is easy to understand. We assume that the first time the browser requests the server, it needs to enter the username and password to verify the identity. The server gets the username and password to the database. If the comparison is correct, it means that the user currently holding this session is a legitimate user, and this session should be marked as "authorized" or "logged in", etc. Since it is the status of the session, it must be saved in the session. In the object, tomcat sets the login status in the session object as follows
1 2 |
## HttpSession session = request.getSession();session.setAttribute("isLogin",true); |
The browser request server model that implements login status is described in the figure below
The login status in the session object is checked every time a protected resource is requested, only isLogin= True session can only be accessed, so the login mechanism is implemented.
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? As described in the figure below
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. Only one login/logout is enough
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
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
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.
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
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
sso authentication center finds that the user is not logged in, and will The user is directed to the login page
The user enters the username and password to submit the login application
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.
The sso authentication center will jump to the original request address (system 1) with the token
System 1 gets the token and goes to the sso certification center to verify whether the token is valid
The sso certification center verifies the token, returns valid, and registers the system 1
System 1 uses this token to create a session with the user, called a partial session, returning the protected resource
User accesses System 2 Protected resources
System 2 finds that the user is not logged in, jumps to the sso authentication center, and uses his own address as a parameter
The sso authentication center finds that the user is logged in, Jump back to the address of System 2 and attach the token
System 2 gets the token and goes to the SSO certification center to verify whether the token is valid
sso authentication center verifies the token, returns valid, registers system 2
System 2 uses the token to create a partial session with the user, and returns protected resources
After the user successfully logs in, a session will be established with the SSO authentication center and each subsystem. The session established by the user with the SSO authentication center is called a global session, and the session established by the user with each subsystem is called a local session. Session, after the local session is established, the user's access to the protected resources of the subsystem will no longer go through the SSO authentication center. The global session and the local session have the following constraint relationship
The local session exists, and the global session must Existence
The global session exists, but the local session does not necessarily exist
The global session is destroyed, and the local session must be destroyed
You can deepen your understanding of single sign-on through the login process of Blog Park, Baidu, csdn, Taobao and other websites. Pay attention to the jump url and parameters during the login process
Naturally, single sign-on also requires single logout. If you log out in a subsystem, the sessions of all subsystems will be destroyed. Use the following figure to illustrate
The SSO authentication center has been monitoring the status of the global session. Once the global session is destroyed, the listener will notify all registered systems to perform logout operations
The following is a brief explanation of the above figure
The user initiates a logout request to System 1
System 1 gets the token based on the session ID established between the user and System 1, and initiates a logout request to the SSO authentication center
The SSO authentication center verifies that the token is valid, destroys the global session, and retrieves all system addresses registered with this token.
The SSO authentication center initiates an initiative to all registered systems Logout request
Each registration system receives the logout request from the SSO authentication center and destroys the partial session
The SSO authentication center guides the user to the login page
Single sign-on involves the SSO authentication center and many subsystems. The subsystems and the SSO authentication center need to communicate to exchange tokens, verification tokens and Initiate a logout request, so the subsystem must integrate the SSO client. The SSO authentication center is the SSO server. The entire single sign-on process is essentially the communication process between the SSO client and the server. Use the following figure to describe it
There are many ways to communicate between the SSO authentication center and the SSO client. Here we take the simple and easy-to-use httpClient as an example. Web service, rpc, and restful api can all be used.
I just briefly introduce the implementation process based on Java, and do not provide the complete source code. If you understand the principle, I believe you can implement it yourself. sso adopts client/server architecture. Let’s first look at the functions to be implemented by sso-client and sso-server (below: sso certification center = sso-server)
sso-client
Intercept the subsystem's non-logged-in user request and jump to the sso authentication center
Receive and store the token sent by the sso authentication center
Communicate with sso-server and verify the validity of the token
Establish a local session
Intercept the user logout request and send it to sso The authentication center sends a logout request
Receives the logout request from the sso authentication center and destroys the local session
sso-server
Verify user’s login information
Create global session
Create authorization token
Communicate with sso-client and send token
Verify the validity of sso-client token
System registration
Receive the sso-client logout request and log out all sessions
Next, let’s implement sso step by step according to the principle!
Java intercepts requests in three ways: servlet, filter, and listener. We use filter. Create a new LoginFilter.java class in sso-client and implement the Filter interface, and add interception of non-logged in users in the doFilter() method
12 | HttpSession session = request. getSession();session.getAttribute("isLogin"); |
1 2 3 4 5 6 7 8 9 10 11 12 |
##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; } //Jump to sso certification center res.sendRedirect("sso-server-url-with-system -url"); } |
3. sso-server verifies user login information
23456@RequestMapping("/ login") | public String login(String username, String password, HttpServletRequest req) {this.checkLoginInfo(username, password);req.getSession(). setAttribute("isLogin",true);return"success";} |
##String token = UUID.randomUUID().toString(); |
5. sso-client obtains the token and verifies it |
## in doFilter() of LoginFilter.java #34567891011//The request comes with the token parameterString token = req.getParameter("token"); | if (token != null) {// Go to the sso certification center to verify the tokenbooleanverifyResult = this.verify("sso-server-verify-url", token);if(!verifyResult) {res.sendRedirect("sso-server-url");return;}chain.doFilter(request, response);} ## The verify() method is implemented using httpClient. This is only briefly introduced. httpClient is used in detail. Please refer to the official documentation for the method |
HttpPost httpPost =new HttpPost(" sso-server-verify-url-with-token");HttpResponse httpResponse = httpClient.execute(httpPost); | 6、 sso-server receives and processes the verification token requestAfter the user successfully logs in to the sso authentication center, sso-server creates an authorization token and stores the token. Therefore, sso-server verifies the token. It is to find whether the token exists and whether it has expired. After the token verification is successful, sso-server will register the system that sent the verification request to the sso certification center (meaning to store it) |
7. sso-client verifies the token and successfully creates the partial session
After the token verification is successful, sso- The client marks the current local session as "logged in", modifies LoginFilter.java, and adds a few lines
1 2if (verifyResult) {session.setAttribute("isLogin",true);} | sso-client also needs to bind the current session id to the token, indicating that the login status of this session is related to the token. This relationship can be saved using java hashmap, and the saved data is used to process the data sent by the sso authentication center. Logout request 8, logout processThe user sends a request with the "logout" parameter (logout request) to the subsystem, and the sso-client interceptor intercepts the request and initiates it to the sso authentication center Logout request
The sso certification center also uses the same method to identify that the sso-client request is a logout request (with the "logout" parameter), the sso certification center Log out of global session
|
The above is the detailed content of Examples to explain the principle of SSO single sign-on. For more information, please follow other related articles on the PHP Chinese website!