Read the harvest

✔️1. Understand the implementation principles of single sign-on

✔️2. Master the xxL-SSO access sso function

Early multi-system login solutions

  • 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.
  • There are many limitations to how cookies can be shared.
      1. The application group domain name must be unified
      1. 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 (tomcat is JSESSIONID) is different, so the session cannot be maintained, and the way of sharing cookie cannot be realized to log in across language technology platforms, such as Java, PHP and.NET systems
      1. Cookies are inherently insecure.
  • Therefore, we need a new login method to realize the multi-system application group login, which is single sign-on

What is single sign-on

  • Single Sign On, or SSO for short.

  • A user can log in to one system in a multi-system application cluster and be authorized to log in to all other systems without having to log in again, including single sign-on and single sign-off

Why is single sign-on required

  • 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?
  • 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

Principle of single sign-on

4.1 the 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

  1. When a user accesses the protected resource 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
  2. The SSO authentication center finds that the user has not logged in and directs the user to the login page (with the system 1 address).
  3. The user enters the user name and password to submit a login application
  4. The SSO authentication center verifies user information, creates a global session between the user and the SSO authentication center, and creates an authorization token
  5. Sso authority jumps to the original request address with the token (System 1)
  6. System 1 obtains the token and goes to the SSO authentication center to verify whether the token is valid
  7. The SSO authentication authority verifies the token, returns valid, and registers system 1
  8. System 1 uses this token to create a session with the user, called a local session, that returns the protected resource
  9. Users access protected resources in system 2
  10. System 2 detects that the user does not log in, switches to the SSO authentication center, and sets its own address as a parameter
  11. When the SSO authentication center detects that the user has logged in, the sso authentication center switches back to the address of system 2 with the token attached
  12. System 2 obtains the token and goes to the SSO authentication center to verify whether the token is valid
  13. Sso authentication center validates token, return valid, register system 2
  14. System 2 uses this token to create a local session with the user and return the protected resource

After successful login, a user establishes a session with the SSO authentication center and the subsystem that the user accesses. The session established between the user and the SSO authentication center is called a global session, and the session established between the user and each subsystem is called a local session. After the local session is established, the user does not access the subsystem protected resources through the SSO authentication center. Global sessions and local sessions have the following constraints

  1. If a local session exists, a global session must exist
  2. Global sessions exist, but local sessions do not necessarily exist
  3. Global session destruction, local session must be destroyed

4.2 cancellation

When you log out of a subsystem, 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

  1. The user sends a logout request to system 1
  2. 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
  3. Sso authenticates that the token is valid, destroys the global session, and extracts all system addresses registered with the token
  4. Sso authentication center sends deregistration requests to all registration systems
  5. Each registration system receives the logout request from the SSO authentication center and destroys the partial session
  6. The SSO authentication center directs the user to the login page

Fast access to SSO

5.1 XXL – sso characteristics

    1. Concise: THE API is intuitive and concise, and can be used quickly
    1. Lightweight: Low environment dependence, low deployment and access costs
    1. Single sign-on (SSO) : You only need to log in once to access all trusted applications
    1. Distributed: Applications that access the SSO authentication center and support distributed deployment
    1. HA: Supports cluster deployment on both servers and clients to improve system availability
    1. Cross-domain: Cross-domain applications can access the SSO authentication center
    1. Cookie+Token: Both Cookie – and token-based access modes are supported, and Sample items are provided
    1. Web+APP: Supports Web and APP access
    1. Real-time: system login and logout status, all Server and Client real-time sharing
    1. CS structure: Based on CS structure, including Server” certification center “and Client” protected application”
    1. Remember the password: If you do not remember the password, close the browser and the login is invalid. When you remember the password, you can automatically postpone the login state. In principle, you can postpone the login state indefinitely
    1. Path exclusion: Multiple user-defined excluded paths and Ant expressions are supported to exclude paths that do not need to be filtered by the SSO client

5.2 environment

  • The JDK: 1.7 +
  • Redis: 4.0 +

5.3 Downloading xxL-SSO source code

Source repository address Release Download
Github.com/xuxueli/xxl… Download
Gitee.com/xuxueli0323… Download

5.4 Document Address

  • Chinese document

5.5 Project structure Description

-XXl-SSO-Server: Central authentication service with cluster support -XXl-Sso-Core: client-side dependencies -xxl-Sso-samples: Single sign-on Client access example Item -xxl-sso-web-sample-springboot: Cookie - based access mode for user browsers. Springboot version -xxl-sso-tok-sample-springboot: The token-based access mode is used in scenarios where cookies cannot be used, for example, apps and cookies are disabled. Springboot versionCopy the code

5.6 Token-based Deployment

  • This section describes token-based deployment only because there are many separate development modes for the front and back ends. This deployment mode can be used in some scenarios where cookies cannot be used, for example, to check the cookie-based deployment

5.6.1 Setting up the SSO Server

  • Project name: XXL-SSO-Server
  • Configuration file location: application.properties
# # # redis address: such as "IP {}", "IP {}, {port}", "{redis/redniss} : / / XXL - sso: {password} @} {IP: {port: 6379} / {db}"; Multiple addresses are separated by commas
xxl.sso.redis.address=Redis: / / 127.0.0.1:6379
The login validity period window is 24 hours by default. When the login validity period window is more than half, it will be automatically extended for another period
xxl.sso.redis.expire.minute=1440
Copy the code

5.6.2 Setting up the SSO Client

  • Project name: xxl-sso-tok-sample-springboot

  • Maven rely on

<dependency>
    <groupId>com.xuxueli</groupId>
    <artifactId>xxl-sso-core</artifactId>
    <version>${latest stable version}</version>
</dependency>
Copy the code
  • Configuration file: application.properties
##### SSO Server Authentication center address (Domain name is recommended)
xxl.sso.server=http://xxlssoserver.com:8080/xxl-sso-server
##### Log out path. The value is the relative path of the Client application
xxl.sso.logout.path=/logout
##### Path excludes Path, allows multiple paths, and supports Ant expressions. This parameter is used to exclude paths that the SSO client does not need to filter
xxl-sso.excluded.paths=
# # # redis / / redis address, like "IP {}", "IP {}, {port}", "{redis/redniss} : / / XXL - sso: {password} @} {IP: {port: 6379} / {db}"; Multiple "," separated
xxl.sso.redis.address=Redis: / / XXL - sso: [email protected]:6379/0
xxl.sso.redis.address=Redis: / / 127.0.0.1:6379
Copy the code
  • Configuration XxlSsoTokenFilter
package com.xxl.sso.sample.config;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.filter.XxlSsoTokenFilter;
import com.xxl.sso.core.util.JedisUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/ * * *@author xuxueli 2018-11-15
 */
@Configuration
public class XxlSsoConfig implements DisposableBean {


    @Value("${xxl.sso.server}")
    private String xxlSsoServer;

    @Value("${xxl.sso.logout.path}")
    private String xxlSsoLogoutPath;

    @Value("${xxl.sso.redis.address}")
    private String xxlSsoRedisAddress;

    @Value("${xxl-sso.excluded.paths}")
    private String xxlSsoExcludedPaths;


    @Bean
    public FilterRegistrationBean xxlSsoFilterRegistration(a) {

        // xxl-sso, redis init
        JedisUtil.init(xxlSsoRedisAddress);

        // xxl-sso, filter init
        FilterRegistrationBean registration = new FilterRegistrationBean();

        registration.setName("XxlSsoWebFilter");
        registration.setOrder(1);
        registration.addUrlPatterns("/ *");
        // The token uses XxlSsoTokenFilter
        registration.setFilter(new XxlSsoTokenFilter());
        registration.addInitParameter(Conf.SSO_SERVER, xxlSsoServer);
        registration.addInitParameter(Conf.SSO_LOGOUT_PATH, xxlSsoLogoutPath);
        registration.addInitParameter(Conf.SSO_EXCLUDED_PATHS, xxlSsoExcludedPaths);

        return registration;
    }

    @Override
    public void destroy(a) throws Exception {

        // xxl-sso, redis closeJedisUtil.close(); }}Copy the code

5.6.3 Authentication (Simulating SSO Access through Token Request)

  • Modify the Host file: access the authentication center using the domain name to simulate the cross-domain and online real environment
Add the following 0 to the host file
127.0.0.1 xxlssoserver.com
127.0.0.1 xxlssoclient1.com
127.0.0.1 xxlssoclient2.com
Copy the code
  • Run “xxL-Sso-server” and “xxL-sso-tok-sample-springboot” respectively

  • After the authentication center is set up successfully, the API interface for Token login is provided by default:

  • 1. Login interface: /app/login

    • Parameter: POST parameter
      • Account username:
      • Your account password:
    • Response: In JSON format
      • Code: 200 indicates success and other failures
      • MSG: error message
      • Data: indicates the sso sessionid of the login user
  • Logout interface: /app/logout

    • Parameter: POST parameter
      • SessionId: indicates the sso sessionId of the login user
    • Response: In JSON format
      • Code: 200 indicates success and other failures
      • MSG: error message
  • 3, login status verification interface: /app/logincheck

    • Parameter: POST parameter
      • SessionId: indicates the sso sessionId of the login user
    • Response: In JSON format
      • Code: 200 indicates success and other failures
      • MSG: error message
      • Data: indicates the login user information
        • Userid: indicates the userid
        • Username: indicates the username
  • Idea HTTP client tests are as follows:

##client1
POST http://xxlssoclient1.com:8082/xxl-sso-token-sample-springboot/
Content-Type: application/x-www-form-urlencoded
xxl_sso_sessionid: 1000_bac4555c627e4233b6da7d3f9b91aff5

###

##client2
http://xxlssoclient2.com:8082/xxl-sso-token-sample-springboot/
Content-Type: application/x-www-form-urlencoded xxl_sso_sessionid: 1000 _bac4555c627e4233b6da7d3f9b91aff5 # # # # # check POST at http://xxlssoserver.com:8080/xxl-sso-server/app/logincheckContent-Type: Application/x - WWW - form - urlencoded sessionId = 1000 _9df8ee645d7f435fb5f76c9223dfe6e8 # # # # # for the POST http://xxlssoserver.com:8080/xxl-sso-server/app/logoutContent-Type: Application/x - WWW - form - urlencoded sessionId = 1000 _0ec8e28158da4241926314e0b3b9b834 login sso POST # # # # http://xxlssoserver.com:8080/xxl-sso-server/app/loginContent-Type: application/x-www-form-urlencoded

username=user&password=123456

Copy the code
  • SSO login/logout process verification:
    • Refer to the test cases: com. XXL. App. Sample. Test. TokenClientTest
  • Normally, the login process is as follows:
    • 1. After obtaining the password entered by the user, request the login interface of the SSO Server to obtain the user SSO sessionid. (reference code: TokenClientTest loginTest)
    • 2. After login, the sso sessionid is obtained, which needs to be actively stored and set in the Header parameter for subsequent requests
    • 3, at this point, the use of sso sessionid access protected “Client01 application” and “application” Client02 provided interfaces, and interface all normal return (reference code: TokenClientTest. ClientApiRequestTest)
  • Normally, the logout process is as follows:
    • 1. Request the logout interface of the SSO Server to logout the login certificate SSO sessionID. (reference code: TokenClientTest logoutTest)
    • 2. After the logout succeeds, the sso sessionid becomes globally invalid
    • If sso sessionID is used to access the interface provided by the protected “Client01 application “and “Client02 Application”, the interface request will be blocked and the status code 501 will be returned. TokenClientTest. ClientApiRequestTest)

6. Overall design

6.1 architecture diagram

6.2 Function Positioning

Xxl-sso is a distributed single sign-on framework. You only need to log in once to access all trusted applications.

With XXL-SSO, you can quickly implement single sign-on (SSO) in distributed systems.

6.3 Core Concepts

concept instructions
SSO Server Central authentication service, support cluster
SSO Client Access the Client application of the SSO authentication center
SSO SessionId Session ID of the login user. If SSO login succeeds, the session ID is automatically assigned to the user
SSO User Login user information, corresponding to SSO SessionId

6.4 Login Process Analysis

  • When a user accesses restricted resources from the Client application, the unified login page is automatically redirected to the SSO Server
  • After a successful login, the SSO SessionId is assigned to the user and the redirect is returned to the source Client application with the assigned SSO SessionId
  • Verify that the SSO SessionId is correct in the SSO Filter of the Client and add the SSO SessionId to the cookie under the Client domain name of the user browser
  • SSO Filter verifies that the SSO SessionId passes, and the restricted resource request is allowed

6.5 Logout Process Analysis

  • When users and Client applications request to deregistration of the Path, the redirect to the SSO Server automatically destroys the global SSO SessionId for global destruction
  • When accessing any Client application that accesses SSO protection, the SSO Filter intercepts the request and redirect it to the unified login page of the SSO Server

6.6 Cookie-based Concepts

  • Login credential storage: After a successful login, the credential is automatically stored in the browser Cookie
  • The Client verifies the login status: verifies whether the Cookie in the request contains user login credentials
  • System role model:
    • SSO Server: authentication center that provides user login, logout, and login status verification

    • Client application: A Client Web application protected by SSO provides services for users’ browser access

    • User: the user who initiates the request and accesses it using a browser

6.7 Token-based concepts

  • Storage of login credentials: After a successful login, the login credentials (xxL_sSO_sessionID = XXX) must be actively stored, for example, in localStorage or Sqlite
  • Verify login status on the Client: Check whether the request Header parameter contains user login credentials (xxl_sSO_sessionID = XXX). Therefore, the login credentials need to be set in the Header parameter when sending the request
  • System role model:
    • SSO Server: authentication center that provides user login, logout, and login status verification
    • Client application: a Client Web application protected by SSO that provides interface services for user requests
    • User: The user who initiates a request, such as an Android, IOS, or desktop client

6.8 Processing Unlogged Status Requests

Cookie based, unlogged status request:

  • Page Request: Redirect to the SSO Server login page
  • JSON request: Returns unlogged JSON-formatted response data
    • Data format:
      • Code: 501 Error code
      • MSG: sso not login.

Token-based unlogged status request:

  • Returns unlogged JSON response data
    • Data format:
      • Code: 501 Error code
      • MSG: sso not login.

6.9 Automatic Login Delay

You can customize the login validity window. The default validity window is 24 hours. When the login validity window reaches half, the validity period is automatically extended.

6.10 Remembering Passwords

If you do not remember the password, close the browser. When you remember the password, the login state is automatically extended. In principle, the extension can be unlimited based on the user-defined extension time.

6.11 Path Exclusion

Custom paths exclude paths, allow multiple paths, and support Ant expressions. This parameter is used to exclude paths that the SSO client does not need to filter.

  • 👍🏻 : have harvest, praise encouragement!
  • ❤️ : Collect articles, easy to look back!
  • 💬 : Comment exchange, mutual progress!