I. Single system login mechanism
1. HTTP stateless protocol
Web applications use browser/ Server architecture and HTTP as the communication protocol. HTTP is a stateless protocol. Each request made by the browser is processed independently by the server, without any connection to previous or subsequent requests. This process is illustrated in the following figure.
But it also means that any user can access server resources through the browser, and if you want to protect some of the server’s resources, you must limit browser requests. To limit browser requests, you must identify browser requests, respond to legitimate requests, and ignore illegal requests. To identify a browser request, you must know the browser request status. Since HTTP is stateless, let the server and browser maintain a state together. This is the conversational mechanism.
2. Conversation mechanism
Browser first request to the server, the server creates a session, and the session id as part of the response sent to the browser, the browser to store session id, and in the subsequent second and third take a session id in the request, the server has requested session id will know whether the same user, this process using an illustration, Subsequent requests are associated with the first request.
The server stores the session object in memory. How does the browser store the session ID? You might think of two ways.
- Request parameters
- cookie
By taking the session ID as a parameter in each request, the server receiving the request can parse the parameter to get the session ID and determine whether it is from the same session. Obviously, this approach is not reliable. It’s up to the browser to maintain the session ID. The browser automatically sends the session ID every time an HTTP request is sent, and cookies are used to do just that. Cookies are a mechanism used by browsers to store a small amount of data in the form of “key/value”. Cookies are automatically attached to HTTP requests sent by browsers.
The Tomcat session mechanism also implements cookies. When you access the Tomcat server, the browser displays a cookie named “JSESSIONID”, which is the session ID maintained by the Tomcat session mechanism. The following figure shows the request response process using cookies.
3. Login status
Login session mechanism, state it is good to see, we assume that the browser first request server needs to input the user name and password authentication, the server to a user name password database, hold this session correctly explain the current user is a legitimate users, should be the session marked as “authorized” or “login” and so on, Since it is the session state, it must be saved in the session object. Tomcat sets the login state in the session object as follows.
HttpSession session = request.getSession(); session.setAttribute("isLogin".true);Copy the code
When the user accesses again, Tomcat checks the login status in the session object
HttpSession session = request.getSession(); session.getAttribute("isLogin");Copy the code
The browser request server model with login state is described in the following figure.
Each time a protected resource is requested, the login status in the session object is checked. Only isLogin=true sessions can access the protected resource, so the login mechanism is implemented.
Second, the complexity of multiple systems
Web system has already developed from a long single system into an application group composed of multiple systems. Facing so many systems, do users need to log in one by one, and then log off one by one? As depicted below.
Web system develops from single system to multi-system application group, the complexity should be borne by the system, not the user. No matter how complex the web system is inside, it is a unified whole for users. That is to say, the whole application group of users accessing the Web system is the same as accessing a single system. Login/logout is enough only once.
While single-system login solutions are perfect, they are no longer suitable for multi-system applications. Why?
The core of the single-system login solution is the cookie, which carries the session ID to maintain the session state between the browser and the server. However, there is a limit to cookies. This limit is the cookie domain (usually the domain name of the website). When a browser sends an HTTP request, it automatically carries cookies that match this domain, not all cookies.
In this case, why not unify the domain names of all subsystems in the Web application cluster under one top-level domain, such as *.baidu.com, and set their cookie field to baidu.com? This is theoretically possible. Even in the early days many systems used cookies shared with domain names.
However, what works is not good, and there are many limitations to how cookies can be shared. First, the application group domain name must be unified; Secondly, the technology used by each system of the application group (at least the Web server) should be the same, otherwise the key value of the cookie (tomcat is JSESSIONID) is different, and the session cannot be maintained. The way of sharing cookie is unable to achieve cross-language technology platform login, such as Java, PHP,.NET systems. Third, cookies are inherently insecure.
Therefore, we need a new login method to realize the multi-system application group login, which is single sign-on.
Single sign-on
What is single sign-on? Single sign-on (SSO for short) means that when you log in to one system in a multi-system application group, you can be authorized to log in to all other systems without having to log in again, including Single sign-on and Single sign-off.
1. Login
Compared with single-system login, sso requires an independent authentication center. Only the authentication center can accept security information such as user names and passwords. Other systems do not provide login portals and only accept indirect authorization from the authentication center. Indirect authorized by token, sso authentication center to verify the user’s user name password no problem, create the authorization token, in the process of the next jump, authorization token as parameters sent to each subsystem, subsystem get tokens, quick to authorize, to create a local session, local session login method with single system login the same way. This process, the principle of single sign-on, is illustrated in the following figure.
Below is a brief description of the figure above.
- When a user accesses the protected resources of system 1, system 1 finds that the user does not log in, switches to the SSO authentication center, and takes its own address as a parameter.
- The SSO authentication center detects that the user has not logged in and directs the user to the login page.
- A user enters a user name and password to submit a login application.
- The SSO authentication center verifies user information, creates a global session between the user and the SSO authentication center, and creates an authorization token.
- Sso authentication authority redirects the original request address with the token (System 1);
- System 1 obtains the token and goes to the SSO authentication center to verify whether the token is valid.
- Sso authentication center validation token, return valid, register system 1;
- System 1 uses this token to create a session with the user, called a local session, which returns the protected resource.
- Users access protected resources in system 2.
- System 2 detects that the user does not log in, switches to the SSO authentication center, and sets its own address as a parameter.
- The SSO authentication center finds that the user has logged in to system 2 and returns to the address with the token attached.
- System 2 obtains the token and goes to the SSO authentication center to verify whether the token is valid.
- Sso authenticates the token, returns valid, registers system 2;
- System 2 uses this token to create a local session with the user and return the protected resource.
After successful login, the user establishes sessions with the SSO authentication center and each subsystem. The sessions established between the user and the SSO authentication center are called global sessions, and those established between the user and each subsystem are called local sessions. After the local sessions are established, the user does not access the subsystem protected resources through the SSO authentication center. Global sessions and local sessions have the following constraints.
- Local session exists, global session must exist;
- Global sessions exist, but local sessions do not necessarily exist.
- Global session destruction, local session must be destroyed.
You can deepen your understanding of single sign-on (SSO) through the login process of blogpark, Baidu, CSDN, Taobao, etc. Pay attention to the jump URL and parameters during the login process.
2, the cancellation
Single sign-on naturally requires single sign-off, logout within a subsystem, and all subsystem sessions are destroyed, as illustrated in the figure below.
The SSO authentication authority always listens for the status of the global session. Once the global session is destroyed, the listener notifies all registered systems to unregister.
Below is a brief description of the figure above.
- The user sends a logout request to system 1
- System 1 obtains the token based on the session ID established between the user and system 1 and sends a deregistration request to the SSO authentication center
- Sso authenticates that the token is valid, destroys the global session, and extracts all system addresses registered with the token
- Sso authentication center sends deregistration requests to all registration systems
- Each registration system receives the logout request from the SSO authentication center and destroys the partial session
- The SSO authentication center directs the user to the login page
Iv. Deployment diagram
Single sign-on (sso) involves the sso authentication center and the subsystem, communication subsystem and sso authentication center needed to exchange tokens, check the token and initiate the cancellation request, therefore subsystem must be integrated sso client, sso authentication center is sso server, the essence of the whole process of single sign-on is the sso client and server communication process, described in below.
The SSO authentication center can communicate with the SSO client in various ways. The following uses the Simple httpClient as an example, including Web Service, RPC, and restful apis.
Five, the implementation
Just a brief introduction to the implementation process based on Java, do not provide complete source code, understand the principle, I believe you can achieve their own. Sso adopts the client/server architecture. Let’s first look at the functions of SSO-client and SSO-Server (following: SSO authentication Center = SSO-server).
sso-client
- Intercepts requests from users who have not logged in to the subsystem and switches to the SSO authentication center.
- Receive and store tokens sent by sso Authentication Authority;
- Communicates with the SSO-server to verify the validity of the token.
- Establish a local session;
- Intercept the user logout request and send the logout request to the SSO authentication center.
- The sso authentication center receives the deregistration request and destroys the local session.
sso-server
- Verify user login information;
- Create a global session;
- Create an authorization token;
- Communicate with SSO-client to send token;
- Verify the validity of the SSO-Client token;
- System registration;
- Receives sSO-Client logout requests and logs out all sessions.
Next, let’s follow the principles step by step to implement SSO!
1. Sso-client intercepts unlogged requests
Java intercepts requests through servlet, Filter, and listener. Filter is used. Create loginfilter. Java class in SSO-client and implement Filter interface, and add interception for unlogged users in doFilter() method.
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;
}
// Switch to the SSO authentication center
res.sendRedirect("sso-server-url-with-system-url");
}
Copy the code
2. Sso-server intercepts unlogged requests
The process of intercepting an unlogged request to redirect to the SSO authentication center from the SSO client is the same as that of the SSO Client.
3. Sso-server verifies user login information
A user enters the user name and password on the login page and requests login. The SSO authentication center verifies the user information. The verification succeeds and the session status is marked as Logged in.
@RequestMapping("/login")
public String login(String username, String password, HttpServletRequest req) {
this.checkLoginInfo(username, password);
req.getSession().setAttribute("isLogin".true);
return "success";
}
Copy the code
4. Sso-server creates an authorization token
An authorization token is a random string of characters and it doesn’t matter how they are generated, as long as they are not duplicated and not easy to forge. Here’s an example.
String token = UUID.randomUUID().toString();
Copy the code
5. Sso-client obtains and verifies the token
After the SSO authentication center logs in, the sso authentication center switches back to the subsystem and attach the token. The subsystem (SSO-Client) obtains the token and verifies it with the SSO authentication center. Add several lines to doFilter() of loginfilter.java.
// Request with token argument
String token = req.getParameter("token");
if(token ! =null) {
// Go to the SSO authentication center to verify the token
boolean verifyResult = this.verify("sso-server-verify-url", token);
if(! verifyResult) { res.sendRedirect("sso-server-url");
return;
}
chain.doFilter(request, response);
}
Copy the code
Verify () is implemented using httpClient, which is described briefly here. For details on how to use httpClient, see the official documentation.
HttpPost httpPost = new HttpPost("sso-server-verify-url-with-token");
HttpResponse httpResponse = httpClient.execute(httpPost);
Copy the code
6. Sso-server receives and processes validation token requests
After a user successfully logs in to the SSO authentication center, the SSO-server creates an authorization token and stores the token. Therefore, the verification of the token by the SSO-server is to check whether the token exists and expires. After successful token verification, the SSO-server registers the system that sent the verification request with the SSO authentication Authority.
The token and registration system address are usually stored in a key-value database (such as Redis), which can set the expiration time (the validity period of the token) for the key. Redis runs in memory and is very fast, just as SSO-Server does not need to persist any data.
Token and registration system addresses can be stored in Redis using the structure described below. You may ask, why store these system addresses? The USER submits a logout request to the SSO authentication center, which deregisters the global session. However, the sso authentication center does not know which systems have established local sessions using the global session, or which subsystems need to send logout requests to deregister local sessions.
7. The SSO-client verifies that the token successfully creates a local session
After the token verification succeeds, the SSO-Client marks the current local session as logged in, modifies loginfilter.java, and adds a few lines.
if (verifyResult) {
session.setAttribute("isLogin".true);
}
Copy the code
Sso-client also needs to bind the current session ID to the token, indicating that the login status of the session is related to the token. This relationship can be saved using Java HashMap, and the saved data is used to process the logout request sent by sso authentication authority.
8. Logout process
A user sends a request (logout request) with the logout parameter to the subsystem. The SSO-Client interceptor intercepts the request and sends the logout request to the SSO authentication authority.
String logout = req.getParameter("logout");
if(logout ! =null) {
this.ssoServer.logout(token);
}
Copy the code
In the same way, the SSO authentication center identifies an SSO-Client request as a logout request (with the logout parameter). The SSO authentication center logs out of the global session.
@RequestMapping("/logout")
public String logout(HttpServletRequest req) {
HttpSession session = req.getSession();
if(session ! =null) {
session.invalidate();/ / triggers LogoutListener
}
return "redirect:/";
}
Copy the code
The SSO authentication authority has a listener for the global session. Once the global session is logged out, all registration systems are notified to log out.
public class LogoutListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent event) {}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
// Send a logout request to all registration systems via httpClient}}Copy the code