It’s a big concept. Just bear with it.
Single sign-on is to solve the multi-system, cross-domain, but only need to log in once can be universal. There are two difficulties
- How to ensure that all subsystems do not need to log in again after one login?
- What if it crosses domains?
How to ensure that all subsystems do not need to log in again after one login?
First of all, how to solve the user login, sent request server know is the user hair?
Common practices include:
- After successful login, the server returns the token. After that, all requests of the client put the token into the Authorization of the request header.
- After successful login, the server writes the SESSIONID into the cookie.
The next request will automatically carry the token, so that the server knows that the request belongs to the user.
If you have logged in to system A but need not log in to system B again, how should the backend be designed?
To do this, two things are needed:
- First, the data layer requires that all users of the system be saved in the SSO system. That is, the user table of the previous article (only the basic public information of users, other information in the form of extended table exists in different systems, ID correlation).
- System A’s login status has to be available to System B.
1 has been solved in the database table design, focus on solving 2.
There are two cases. If it is from system A to system B, it can directly put the token in the link to jump, so that system B can directly get the login state of system A by parsing the parameters. If you open the homepage of system B, you can store the login state in cookies. Cookies of the same domain name are universal (different domain names will be involved here, as described later).
Up to now, system B has got the login state of system A, how to change it into the login state of system B?
It also depends on how the systems are designed. If system A and SYSTEM B share the same token, no additional operations are required. In most cases, system A and SYSTEM B do not share the same token. In this case, an extra step is required. System B requests the SSO server to exchange system A’s token for system B’s token.
Let me show you a flow chart.
How are tokens stored?
The token is recommended to be stored in Redis.
After defining the storage specification of tokens, we only need to clear all tokens of the system during logout to ensure that all tokens are logged out.
For example, each system token has the same key and is distinguished in value. The key uses the first 10 digits of each token. The tokens in different systems store different keys, but the keys in different systems of the same user are associated. And ensure that any system request to log out, can find other system tokens and clean up.
Let’s do a flow chart.
What if it crosses domains?
- The URL carries a token
- Cookie sets the desired domain and path
- After a domain obtains a token, JS actively stores the token in other domains.