Single sign on (SSO)


Login is a function often used in every website. On the page, we enter the account password and click enter to log in, but do you know the login principle behind it?

Traditional login method

The most original login method is that each website has its own login system and independent account. Users need to log in again when accessing each system. Accounts cannot be shared between systems, and the login status cannot be shared, which will lead to some disadvantages:

  • When employees need to use multiple internal systems of the company, they need to register an account in each system. If an employee leaves, each system also needs to delete the account information of the employee
  • Obviously, this user is using the system, but he has to log in multiple times

Single sign on (SSO)

The root of the disadvantages of the above login method is that the login status of users cannot be shared. What does “status” mean? How to realize “state sharing”?

Stateful and stateless

We all knowHTTPIt is a stateless protocol. Each time the client sends a request, it must first establish a connection with the server, and then disconnect the connection after the request is completed. This method can save the connection resources occupied during transmission, but there is also a problem: each request is independent. The server cannot judge whether this request and the last request come from the same user, and then cannot judge the user’s login status.

In order to solveHTTPStateless problems,Lou MontulliIn 1994, it was launchedCookie

CookieIt is a piece of special information sent by the server to the client. These information are stored in the client in the form of text. The client will bring these special information every time it sends a request to the server.

YesCookieAfter that, the server can get the information passed by the client. If you need to authenticate the information, you also need to pass theSession

The client requests the server, and the server will open up a memory space for this request. This isSessionObject.SessionObject is used to record the login information of usersSessionEach object has a correspondingsidsidIs unique. After successful login, the server willsidInject intocookieIn, the next login or request will carry thecookieConduct certification

YesCookieandSessionAfter that, we can log in and authenticate.

Explain the meaning of authentication and authorization: authentication refers to checking whether the user has logged in; Authorization refers to what the user can do, such as what menus the user can see

Cookie + Session

Cookie + SessionThe login method is the most classic login method, which is still used by a large number of enterprises.

Single login

Single sign on (SSO)

When a user logs in for the first time:

Single sign on (SSO)

User, and enter the password to log in. After the server verifies that the password is correct, aSessionIdAnd save it. The server responds to thisHTTPRequest and passSet-CookieHeader information, willSessionIdwrite inCookieYes.

Server sideSessionIdIt may be stored in many places, such as memory, files, databases, etc.

After the first login, subsequent accesses can be used directly CookieAuthenticated:

Single sign on (SSO)

User will be automatically loaded with the information written during the first loginCookie。 Server side comparisonCookieMediumSessionIdAnd stored on the server sideSessionIdConsistency. If consistent, authentication is successful.

Monomer cluster

When the traffic is high, the above server can not support it, so it is necessary to cluster the servers

Single sign on (SSO)

In addition, reverse proxy has two functions:

  • Request distribution, load balancing, reducing node server access pressure
  • eachCookieAll correspond to onedomaina.comThe request under the domain name will only carry the information in the domain nameCookie, visitb.comPage will not be carrieda.comIn domain nameCookie, through reverse proxy to the same domain name (, each node server can receive cookies under the domain name (

At the same time,SessionCannot be stored on the server of each nodetomcatIn memory, it will causeSessionCannot share when accessing froma.comSwitch tob.comYou need to log in again. In order that each node server can shareSessiontomcatThere is a built-in cluster method, which can synchronously replicate nodestomcatIn memorySession, just modify the Tomcat configuration file:

  • modifyserver.xml, uncomment<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
  • Modify applicationweb.xml, add nodes<distributable />

However, this method has the following disadvantages:

  • Each service needs to modify the configuration file
  • Occupied bandwidth
  • Replication occurs when the server runs out of memorySessionMay causeSessionlose

Is there a better way to solve itSeesionWhat about consistency?

File system? database Distributed cache?

In fact, all these are OK, but the performance is different. The performance of file system and database will not be very high. Distributed cache solves this problem

There are two types of distributed cache: 1MenCache;2、Redis; It will still be used in more scenariosRedisStorage.ConcurrentHashMapStorage usedJVMHeap memory, andRedisPhysical memory is used.

Single sign on (SSO)

Session single sign on

The above is the login of one system. What if we want to log in to multiple systems with one account?

Single sign on (SSO)

Through reverse proxy to the same domain name (, each node server can receive cookies under the domain name (, but how do we know which cluster website users like to visit?

The solution isReverse proxy the site to the same domain nameAnd establishMapping relationship between route or secondary domain name and cluster siteGenerally, routing is used for mapping to determine which cluster site users want to visit, and finally poll which node services are distributed to


Problems with cookie + session

Although we useCookie + SessionThe login verification is completed in the following way, but there are still some problems:

  • Because the server needs to connect with a large number of clients, it needs to store a large number of dataSession, this will cause excessive pressure on the server.
  • If the server side is a cluster, use seesion to copy the synchronous login status. You need toSessionSynchronization to each machine virtually increases the server-side maintenance cost.

Cookie + Token

In order to solveSession + CookieThe mechanism exposes many problems that we can useTokenLogin method.

TokenIs a string generated by the server as a token requested by the client. After the first login, the server generates aTokenAnd return it to the client. When the client accesses later, it only needs to bring thisTokenYou can complete identity authentication.

Single login

Single sign on (SSO)

When a user logs in for the first time:

Single sign on (SSO)

  • The user enters the account password and clicks login.
  • The server side verifies that the account and password are correct and createsToken
  • The server side willTokenReturned to the client byClient free save
  • When accessing subsequent pages:

Single sign on (SSO)

  • User logging in, bring the information obtained at the first loginToken
  • Server side authenticationToken, valid, authentication succeeds.

Characteristics of token mechanism

According to the above case, we can analyze TokenAdvantages and disadvantages of:

  • No storage is required on the server sideTokenTherefore, there is no pressure on the server side, and even the server cluster does not need to increase the maintenance cost.
  • TokenIt can be stored anywhere in the front end without saving it in the CookieThe security of the page is improved.
  • TokenAfter distribution, it will remain valid as long as it is within the effective time. If the server wants to withdraw this informationToken Access is not easy.

How to generate a token

implementationTokenThere are many verification methods, as well as some standard methods, such as JWT, read:jot, indicating:JSON Web TokensJWTStandardTokenThere are three parts:

  • Header
  • Payload (data)
  • Signature

The middle is separated by dots and will be usedBase64 Coding, so realTokenIt looks like this:


eachJWT tokenThere’s one in itheader, that is, header data. It contains the algorithm used, thisJWTIs it signed or encrypted. It mainly explains how to deal with thisJWT token

The contents of the head may vary according to JWTThe type of is changed, such as an encrypted oneJWTIt should include the encryption algorithm used. The only attribute to be included in the header is alg. If it is encryptedJWT, the value of this attribute is the signature or decryption algorithm used. If unencryptedJWT, the value of this property should be set to none

The shape is as follows:

  "alg": "HS256",
  "typ": "JWT"

It means thisJWTThe algorithm used isHS256。 The above content is usefulbase64urlCode in the form of, so it becomes like this:


This partJSONafterBase64Formed after codingTokenThe first part of.


PayloadInsideTokenSome of these contents are standard fields. You can also add other required contents. Here are the standard fields:

  • ISS: issuer
  • Sub: subject, subject
  • Aud: audience
  • Exp: expiration time
  • nbf:Not before
  • IAT: issued at, issue time
  • jti:JWT ID

Like this one belowPayload, yesissIssuer, and expExpiration time these two standard fields. There are also two custom fields. One isname, another one isadmin

 "iss": "",
 "exp": "1438955445",
 "name": "wanghao",
 "admin": true

usebase64urlAfter coding, it becomes like this:


JWTThe last part isSignature, there are three parts in this part. First, useBase64Codedheader.payload, then use the encryption algorithm to encrypt it. When encrypting, put one inSecret, this is equivalent to a password, which is secretly stored on the server.

  • header
  • payload
  • secret
const encodedString = base64UrlEncode(header) + "." + base64UrlEncode(payload); 
HMACSHA256(encodedString, 'secret');

After processing, it looks like this:


Finally, this is generated on the server and sent to the clientTokenIt looks like this:


The client received thisTokenStore it later, and bring it when sending a request back to the serverToken。 The server received thisToken, and then verify it. After it passes, it will return to the resources the client wants.

Issue and verify JWT

Application Based JWT such TokenYou can find an authentication method to sign and verifyJWTFeature Pack. No matter what programming language, system, or framework your back-end application uses, you should be able to find packages that provide similar functions.

Issue JWT

Add any one in the project.jsFiles, such asindex.js, add the following codes to the file:

const jwt = require('jsonwebtoken')

//Token data
const payload = {
  name: 'wanghao',
  admin: true

const secret = 'ILOVENINGHAO'

//Issue token
const token = jwt.sign(payload, secret, { expiresIn: '1day' })

//Output issued token

Very simple, just use itjsonwebtokenIt’s provided insidejwt.signFunction to sign and issue atoken。 thissignMethod requires three parameters:

  • Playload: some data to be included in the issued token.
  • Secret: the key used to sign and issue the token. This key is also needed when verifying the token.
  • Options: some other options.
Verify JWT

verificationJWTTo determine the user’s effectivenessJWTIt’s signed and issued by ourselves. First of all, we need to get this from the userJWT Token, and then usejwt.verifyThis method is used to verify. If not, you should do it yourselfSecretIssuedToken, the verification will fail. This method isNode.jsYesjsonwebtokenProvided in this package, you may find similar methods to verify in other application frameworks or systemsJWT

//Verify token
jwt.verify(token, 'secret', (error, decoded) => {
  if (error) {

Token monomer cluster

Single sign on (SSO)

Token single sign on

Single sign on (SSO)

What problems may you encounter when using token?

  1. Can the token be stolen?

    Token is not easy to steal in HTTPS protocol,httpsMediumSSLThe protocol encrypts the request header and request body, that is, the data transmitted to the serverCookieIt is encrypted, and it is not easy to decrypt if the request is intercepted. Of course, if your computer is installed with some malicious programs implanted with Trojans to steal your account and token, there is no way, so you still advocate healthy Internet access and refuse pirated software.

  2. What if the key is directly placed in the server and stolen by the developer?
    What if you can’t prevent fire and theft? Generally, the key will not be placed directly in the project, but may be placed in the file system orgithubAnd different environments have different keys. In order to prevent developers from printing after reading the key, a code review link can be added, and the submitted code will be automatically scanned. If the key code of the printed key is found, the employee will be dismissed decisively. In addition, the key may be changed from time to time.
  3. How to renew a token?
    The validity period of the token is up. If you ask the user to go through the above process again and apply for a new token, it is likely to have a bad experience and is not necessary. The specific method is that when the server issues a token, it issues two tokens at one time, one for obtaining data and the other for obtaining a new token (refresh token field). Before token expiration(The front-end countdown determines the expiration or requests to find login exceptions), the user sends a request using refresh token to update the token.


Whether usedSessionstillTokenTo realize single sign on, each subsystem above needs to implement its own authentication service, but theirSessionperhapsTokenThey are shared and can be separated into a central authentication service(CAS), all subsystems log in and authenticate through the central authentication service.

CASyesCentral Authentication ServiceAbbreviation for central authentication service, an independent open instruction protocol.CASyes YaleAn open source project initiated by the university aims to provideWeb The application system provides a reliable single sign on method.CAS It consists of two parts:CAS ServerandCAS ClientCAS ServerIt needs to be deployed independently and is mainly responsible for user authentication;CAS ClientIt is responsible for processing access requests to client protected resources. When login is required, it is redirected toCAS Server

Single sign on (SSO)

CAS ClientDeploy with protected client applications toFilter Way to protect protected resources. For each access to a protected resourceWebRequest,CAS ClientThe request will be analyzedHttpDoes the request containService TicketIf not, it means that the current user has not logged in, so the request is redirected to the specified userCAS ServerLogin address and passService(that is, the destination resource address to be accessed) so that you can return to the address after successful login. The user enters the authentication information in step 3. If the login is successful,CAS ServerRandomly generate a considerable length, unique and unforgeableService Ticket, and cache for future verification, and then the system automatically redirects toServiceAddress and set one for the client browserTicket Granted Cookie(TGC)CAS ClientIn getting ServiceAnd newTicketAfter that, in steps 5 and 6CAS ServerConduct identity verification to ensureService TicketLegitimacy of.

In this agreement, allCAS All interactions areSSL Agreement to ensure that,ST andTGCSecurity. There will be two redirections during the protocol work, butCAS ClientAndCAS ServerBetweenTicket The process of authentication is transparent to users.

In addition,CASThe protocol also providesProxy(agent) mode to adapt to more advanced and complex application scenarios. For details, please refer to CASRelevant documents on the official website.

Single sign on (SSO)

The picture above isCASThe standard process on the official website is as follows:

  1. User accessappSystem,appThe system needs to log in, but the user is not logged in now.
  2. Jump toCAS server, i.eSSOLog in to the system, and thenCAS ServerWe are collectively calledSSOSystem. SSOThe system does not log in, and the user login page pops up.
  3. The user fills in the user name and password,SSOAfter the system authenticates, write the login status toSSOYessession, browser(Browser)Write inSSOUnder domainCookie
  4. SSOAfter the system login is completed, aST(Service Ticket), then jump toappSystem, andSTPass as parameter toappSystem.
  5. appSystem getSTFrom the background to theSSOSend request, verifySTWhether it is valid.
  6. After verification,appThe system writes the login status tosessionAnd setappUnder domainCookie

At this point, cross domain single sign on is complete. We’ll visit laterappWhen using the system,appIs to log in. Next, let’s look at the interviewapp2The process of the system.

  1. User accessapp2System,app2The system is not logged in, jump toSSO
  2. becauseSSOYou have already logged in. You don’t need to log in again for authentication.
  3. SSOgenerateST, the browser jumps toapp2System, andSTPass as parameter toapp2
  4. app2GetST, background accessSSO, verifySTWhether it is valid.
  5. After successful verification,app2Write login status tosession, and inapp2Write under domainCookie


In the traditional client server authentication mode, when a client requests access to a restricted resource (protected resource) on the server, it needs to use the credentials of the resource owner to authenticate on the server. In order to provide third-party applications with access to restricted resources, the resource owner needs to share its credentials with the third party. This leads to some problems and limitations:

  • Third party applications need to store the credentials of the resource owner for future use. This credential is usually a clear text password.
  • The server needs to support password authentication, although password authentication has inherent security defects.
  • The third-party application obtains too broad access to the protected resources of the resource owner, so that the resource owner cannot limit the access time limit or permission to a limited subset of resources.
  • The resource owner cannot revoke the access rights of a third party without affecting other third parties, and must change their password to do so.
  • A compromise with any third-party application results in a compromise on the end user’s password and all data protected by the password.

OAuth solves these problems by introducing an authorization layer and separating the client role from the resource owner role.In detail,OAuthAn authorization layer is set between “client” and “service provider”(authorization layer)。” The client “cannot log in to the” service provider “directly, and can only log in to the authorization layer, so as to distinguish the user from the client.” Token used by the client to log in to the authorization layer(token), different from the user’s password. The user can specify the permission range and validity period of the authorization layer token when logging in“ After the client “logs into the authorization layer,” the service provider “opens the data stored by the user to the” client “according to the authority range and validity period of the token.

Difference between CAS and oauth2

  • CASEnsure the security of user resources on the client during single sign on,OAuth2Is to ensure the security of user resources on the server;
  • CASThe final information the client wants to get is whether the user has permission to access me(CAS(client) resources;oauth2The final message is that I(oauth2Can the user’s resources of the service provider let you(oauth2Client access;
  • CASSingle sign on, resources are on the client side, not on the client sideCASOn the server side. The user is givingCASAfter the server provides the user name and password, asCASThe client doesn’t know about it. Just give the client oneST, then the client cannot determine thisSTIs it forged by the user or really effective, so take thisSTGo to the server and ask again. What this user gave me is validSTIt’s still invalidST, is valid, I can let this user access.
  • OAuth2Certification and resources are availableOAuth2On the side of the service provider, the client wants to request the user’s resources. Therefore, in the most secure mode, the server cannot return directly after user authorizationtoken, send it to the client through redirection because of thistokenIt may be intercepted by hackers. If hackers intercept thistoken, then the user’s resources are exposed to the hacker. So the smart server sends an authenticationcodeTo the client (through redirection), the client is in the background, throughhttpsIn this waycode, and another string of pre negotiated passwords between the client and the server can be obtainedtokenAnd refreshtoken, this process is very safe. If the hacker intercepts itcode, he didn’t have the agreed password, and he couldn’t get ittokenYes. suchoauth2You can ensure that the request for resources is agreed by the user and the client is recognized. You can safely send resources to the client.
  • CASLogin andOAuth2The biggest difference in the process is throughSTperhapscodeWhen you go to authentication, do you need a pre negotiated password.

OAuth defines four roles:

  • Resource owner
    An entity that can grant access to protected resources. When the owner of a resource is an individual, it is called an end user.
  • Resource server
    The server hosting protected resources can receive and respond to requests for protected resources using access tokens.
  • client
    An application that uses the authorization of the resource owner to initiate requests for protected resources on behalf of the resource owner. The term “client” does not refer specifically to any specific implementation feature (for example, whether the application is executed on a server, desktop or other device).
  • Authorization server
    Issue the access token to the server of the client after the resource owner is successfully verified and authorized.

The interaction between the authorization server and the resource server is beyond the scope of this specification. The authorization server can be the same server as the resource server, or it can be a separate individual. An authorization server can issue access tokens accepted by multiple resource servers.

Abstract protocol flow

+--------+                               +---------------+
 |        |--(A)- Authorization Request ->|   Resource    |
 |        |                               |     Owner     |
 |        |<-(B)-- Authorization Grant ---|               |
 |        |                               +---------------+
 |        |
 |        |                               +---------------+
 |        |--(C)-- Authorization Grant -->| Authorization |
 | Client |                               |     Server    |
 |        |<-(D)----- Access Token -------|               |
 |        |                               +---------------+
 |        |
 |        |                               +---------------+
 |        |--(E)----- Access Token ------>|    Resource   |
 |        |                               |     Server    |
 |        |<-(F)--- Protected Resource ---|               |
 +--------+                               +---------------+

The abstract shown in the figureOAuth 2.0The process describes the interaction between the four roles, including the following steps:

(A) The client requests authorization from the resource owner. The authorization request can be initiated directly to the resource owner (as shown in the figure), or preferably indirectly through the authorization server as an intermediary.
(B) The client receives an authorization license, which is an authorization credential on behalf of the resource owner. It is represented by one of the four license types defined in this specification or by an extended license type. The type of authorization depends on the method used by the client to request authorization and the type supported by the authorization server.
(C) The client authenticates with the authorization server and presents the authorization permission to request an access token.
(D) The authorization server verifies the identity of the client and verifies the authorization license. If it is valid, it issues an access token.
(E) The client requests a protected resource from the resource server and presents an access token for authentication.
(F) The resource server verifies the access token and processes the request if it is valid.
A better way for a client to obtain authorization from the resource owner (as shown in steps (a) and (b)) is to use the authorization server as an intermediary

Authorization permission is a credential that authorizes (access to protected resources) on behalf of the resource owner, which is used by the client to obtain an access token.RFC 6749The specification defines four license types — authorization code, implicit license, resource owner password credentials, and client credentials — and extensibility mechanisms for defining other types.

Taking GitHub authorization as an example, this paper describes the type of authorization code

First, you need togithubApply for registration on. After registrationGitHubThe client is returnedID(client_id)And client key(client_secret

Single sign on (SSO)

Client front endSessionMode certification:

Single sign on (SSO)

Client front endTokenMode certification:

Single sign on (SSO)

reference resources:
Token based authentication: JSON web token (attached: node.js project)
Seesion replication
Four ways of Ruan Yifeng OAuth 2.0
RFC 6749 Chinese version
RFC 6749 OAuth 2.0 authorization framework simplified Chinese Translation
github OAuth documentation