Home > Backend Development > PHP Tutorial > Examples to explain the principle of SSO single sign-on

Examples to explain the principle of SSO single sign-on

小云云
Release: 2023-03-20 21:04:02
Original
3234 people have browsed it

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

Examples to explain the principle of SSO single sign-on

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

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

Examples to explain the principle of SSO single sign-on

# 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

# 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

Examples to explain the principle of SSO single sign-on

3. Login status

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);

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

The browser request server model that implements login status is described in the figure below

Examples to explain the principle of SSO single sign-on

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.

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? As described in the figure below

Examples to explain the principle of SSO single sign-on

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

Examples to explain the principle of SSO single sign-on

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

Examples to explain the principle of SSO single sign-on

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. The sso authentication center finds that the user is logged in, Jump back to the address of System 2 and attach the token

  12. System 2 gets the token and goes to the SSO certification center to verify whether the token is valid

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

  14. 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

  1. The local session exists, and the global session must Existence

  2. The global session exists, but the local session does not necessarily exist

  3. 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

2. Logout

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

Examples to explain the principle of SSO single sign-on

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

  1. The user initiates a logout request to System 1

  2. 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

  3. The SSO authentication center verifies that the token is valid, destroys the global session, and retrieves all system addresses registered with this token.

  4. The SSO authentication center initiates an initiative to all registered systems Logout request

  5. Each registration system receives the logout request from the SSO authentication center and destroys the partial session

  6. The SSO authentication center guides the user to the login page

4. Deployment diagram

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

Examples to explain the principle of SSO single sign-on

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.

5. Implementation

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

  1. Intercept the subsystem's non-logged-in user request and jump to the sso authentication center

  2. Receive and store the token sent by the sso authentication center

  3. Communicate with sso-server and verify the validity of the token

  4. Establish a local session

  5. Intercept the user logout request and send it to sso The authentication center sends a logout request

  6. Receives the logout request from the sso authentication center and destroys the local session

sso-server

  1. Verify user’s login information

  2. Create global session

  3. Create authorization token

  4. Communicate with sso-client and send token

  5. Verify the validity of sso-client token

  6. System registration

  7. Receive the sso-client logout request and log out all sessions

Next, let’s implement sso step by step according to the principle!

1. sso-client intercepts non-login requests

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

1

2

HttpSession session = request. getSession();

session.getAttribute("isLogin");

2. sso-server intercepts non-login requests

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");

}

Intercepts requests from sso-client Jump to the non-login request of the sso authentication center and jump to the login page. This process is exactly the same as sso-client

3. sso-server verifies user login information

The user is on the login page Enter the user name and password, request login, the SSO certification center verifies the user information, the verification is successful, and the session status is marked as "Logged in"

##14、sso-server Create an authorization token
2

3

4

5

6

@RequestMapping("/ login")
public String login(String username, String password, HttpServletRequest req) {

this.checkLoginInfo(username, password);

req.getSession(). setAttribute("isLogin",true);

return"success";

}

The authorization token is a string of random characters. It doesn’t matter how it is generated, as long as it is not repeated and cannot be easily forged. Here is an example

15. sso-client obtains the token and verifies it After logging in to the sso authentication center, jump back to the subsystem and attach the token. The subsystem (sso-client) obtains the token, and then Go to the sso certification center for verification and add a few lines

##String token = UUID.randomUUID().toString();

12
## in doFilter() of LoginFilter.java #3

4

5

6

7

8

9

10

11

//The request comes with the token parameter

String token = req.getParameter("token");
if (token != null) {

// Go to the sso certification center to verify the token

booleanverifyResult = 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

##1

2 Token and registration The system address is usually stored in a key-value database (such as redis). Redis can set the validity time for the key, which is the validity period of the token. Redis runs in memory and is very fast. It happens that sso-server does not need to persist any data.
HttpPost httpPost =new HttpPost(" sso-server-verify-url-with-token");

HttpResponse httpResponse = httpClient.execute(httpPost);

6、 sso-server receives and processes the verification token request

After 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)
Tokens and registration system addresses can be stored in redis using the structure described in the figure below. You may ask, why should the addresses of these systems be stored? If it is not stored, it will be troublesome when logging out. The user submits a logout request to the SSO authentication center, and the SSO authentication center logs out the global session. However, it does not know which systems have used this global session to establish their own local sessions, nor which sub-sessions they need to send to the SSO authentication center. The system sends a logout request to log out the partial session

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

Examples to explain the principle of SSO single sign-on

1

23

if (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 process

The 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

1

2

3

4

String logout = req.getParameter("logout");

if (logout != null) {

this.ssoServer.logout(token);

}

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

##1

2

3

4

5

6

7

8

@RequestMapping("/logout")

public String logout (HttpServletRequest req) {

HttpSession session = req.getSession();

if(session != null) {

session.invalidate();//Trigger LogoutListener

}

return"redirect:/";

}

The sso certification center has a The listener of the global session. Once the global session is logged out, all registered systems will be notified to log out

## Related recommendations:
1

2

3

4

5

6

7

8

public class LogoutListener implementsHttpSessionListener {

@Override

publicvoid sessionCreated(HttpSessionEvent event) {}

@Override

publicvoid sessionDestroyed(HttpSessionEvent event) {

// Send a cancellation request from all the registration system through httpclient

#}

}

Single sign-on cookie analysis and implementation in PHP

Single sign-on principle and simple implementation

SSO single sign-on PHP implementation method (Laravel framework)

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!

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