What is single sign-on (SSO)? Single sign-on (SSO) in the end what does that mean? [Examples] Demo logic attachment

Copyright: Life program https://blog.csdn.net/cnpinpai/article/details/90669587

     In application development, especially the development of the class Web site, will be exposed to a single sign-on (SSO) , what is the single sign-on ? , Single sign-on (SSO) What is the use? The following soft money network Xiaobian to introduce:

First, what is the single sign-on?

Single sign-English name is called: Single Sign On (referred to as SSO ).

In the beginner / previous time, we generally single system , all functions on the same system.

Single sign-on (SSO)
Single sign-on (SSO)

 

Later, we for rational use of resources and reduce the coupling , so the single-system split into a plurality of subsystems.

  • Review: Distributed Basics
Single sign-on (SSO)
Single sign-on (SSO) - Yu Butler

Split into a plurality of sub-

Such as Ali's Taobao and Tmall , it is clear that we can know that this is the two systems, but when you're used to log the Lynx, Taobao will automatically log on.

Single sign-on (SSO)
Single sign-on (SSO)

 

In simple terms, is the single sign-on across multiple systems, users simply log on once, each system can sense the user has logged in.

Second, the review of the single system login

When I was a beginner JavaWeb, login and registration is a feature I have done most of the (beginner when the Servlet done, when the school SpringMVC done, followed by doing the project did ...), anyway, I can not count how many times do I login and registration functions of here ... when we talk briefly about the beginner is how to do sign-on function.

HTTP is a stateless protocol

As we all know, HTTP is a stateless protocol, which means that the server can not confirm the information of the user . Ever since, W3C put forward: to each client is sent a pass to access all the time no matter who need to carry a pass, so that the server can confirm the user's information from the pass. Pass is Cookie .

If Cookie is to check the user's body "pass" to confirm the identity of the user, then the Session is to confirm the identity of users through the "customer list" to check on the server. Session equivalent to establish a "customer list" in the server .

HTTP protocol is stateless, Session based HTTP connection can not be determined whether the same user. Ever: The server sends a Cookie named JESSIONID to the user's browser, its value is the value of the Session id. In fact, according to the Cookie Session is to identify whether the same user .

So, in general we do log on to achieve a single system:

  • Login : User information is stored in the Session object
  • - if they can be found in the Session object, explained that it had Login
  • If you can not find in the Session object, it shows no sign in (or has withdrawn login)
  • Logout (Log) : delete user information from the Session
  • Remember me (after close out your browser and re-open the browser can stay logged in) : to cooperate with Cookie

Before I Demo code, you can refer to:

/**
 * 用户登陆
 */
@PostMapping(value = "/user/session", produces = {"application/json;charset=UTF-8"})
public Result login(String mobileNo, String password, String inputCaptcha, HttpSession session, HttpServletResponse response) {
 //判断验证码是否正确
 if (WebUtils.validateCaptcha(inputCaptcha, "captcha", session)) {
 //判断有没有该用户
 User user = userService.userLogin(mobileNo, password);
 if (user != null) {
 /*设置自动登陆,一个星期. 将token保存在数据库中*/
 String loginToken = WebUtils.md5(new Date().toString() + session.getId());
 user.setLoginToken(loginToken);
 User user1 = userService.userUpload(user);
 session.setAttribute("user", user1);
 CookieUtil.addCookie(response,"loginToken",loginToken,604800);
 return ResultUtil.success(user1);
 } else {
 return ResultUtil.error(ResultEnum.LOGIN_ERROR);
 }
 } else {
 return ResultUtil.error(ResultEnum.CAPTCHA_ERROR);
 }
}
/**
 * 用户退出
 */
@DeleteMapping(value = "/session", produces = {"application/json;charset=UTF-8"})
public Result logout(HttpSession session,HttpServletRequest request,HttpServletResponse response ) {
 //删除session和cookie
 session.removeAttribute("user");
 CookieUtil.clearCookie(request, response, "loginToken");
 return ResultUtil.success();
}
/**
* @author ozc
* @version 1.0
* <p>
* 拦截器;实现自动登陆功能
*/
public class UserInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
 User sessionUser = (User) request.getSession().getAttribute("user");
 // 已经登陆了,放行
 if (sessionUser != null) {
 return true;
 } else {
 //得到带过来cookie是否存在
 String loginToken = CookieUtil.findCookieByName(request, "loginToken");
 if (StringUtils.isNotBlank(loginToken)) {
 //到数据库查询有没有该Cookie
 User user = userService.findUserByLoginToken(loginToken);
 if (user != null) {
 request.getSession().setAttribute("user", user);
 return true;
 } else {
 //没有该Cookie与之对应的用户(Cookie不匹配)
 CookieUtil.clearCookie(request, response, "loginToken");
 return false;
 }
 } else {
 //没有cookie、也没有登陆。是index请求获取用户信息,可以放行
 if (request.getRequestURI().contains("session")) {
 return true;
 }
 //没有cookie凭证
 response.sendRedirect("/login.html");
 return false;
 }
 }
}
}

Summarize the ideas above code:

  • When users log on, verify that the user account and password
  • Generating a Token stored in the database, the Token wrote the Cookie
  • The user data in Session
  • When the request will bring Cookie, check if any login, if you are already logged released

What is the role of Cookie? And Session What is the difference?

Cookie and Session session are used to track the identity of the browser user mode, but both scenarios are not the same.

Cookie generally used to store user information  such as ① we save in the Cookie has a nice user login information next time you visit the site when the page is automatically some basic information to help you log in to fill; ② general site also will have to remain logged in that is when the next time you visit the site you do not need to re-login, this is because when the user logs in, we can store in a Token Cookie, the next time you log in only to find a user based on Token value to ( for security reasons, we want to re-sign in general Token rewrite); ③ log in once after the site visit other pages do not need to log in again. The main effect of Session is the status of the user record by the server. A typical scenario is a shopping cart, when you want to add items to the shopping cart, the system does not know which user actions, because the HTTP protocol is stateless. After the server to create specific Session to a particular user can identify the user and tracks the user the.

Cookie data stored in the client (browser), Session data is stored on the server side.

Cookie is stored in the client, and stored on the server Session, Session is relatively more secure. If you are using the Cookie Cookie sensitive information is not written, it is best able to Cookie information is then used to encrypt the time to go to the server to decrypt.

Third, multi-system login problems and solutions

3.1 Session does not share issue

Single system login function is to store user information with Session to achieve, but we are clear: namely multi-system may have multiple Tomcat, while Session is dependent on the current system of Tomcat, so Session Session A and system B system is do not share in.

Session Session A and the system B is not shared
Session Session A and system B are not shared in the opinion Po

Session solve the system is not shared between the issues at several options:

  • Tomcat Session global cluster replication (session within each cluster tomcat fully synchronized) [it will affect the performance of the cluster is not recommended]
  • According to the request of IP Hash mapped to the corresponding machine (which is equivalent to the request of IP will have access to the same server) [If the server is down, will lose a large part of Session data is not recommended]
  • The Session on Redis data (using Redis Analog Session) [ recommended ]

We can login function alone extracted out, made a subsystem.

What is single sign-on (SSO)? Single sign-on (SSO) in the end what does that mean?

Extracted become Subsystem

The SSO (system log) of the logic is as follows:

// 登录功能(SSO单独的服务)
@Override
public TaotaoResult login(String username, String password) throws Exception {
 //根据用户名查询用户信息
 TbUserExample example = new TbUserExample();
 Criteria criteria = example.createCriteria();
 criteria.andUsernameEqualTo(username);
 List<TbUser> list = userMapper.selectByExample(example);
 if (null == list || list.isEmpty()) {
 return TaotaoResult.build(400, "用户不存在");
 }
 //核对密码
 TbUser user = list.get(0);
 if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
 return TaotaoResult.build(400, "密码错误");
 }
 //登录成功,把用户信息写入redis
 //生成一个用户token
 String token = UUID.randomUUID().toString();
 jedisCluster.set(USER_TOKEN_KEY + ":" + token, JsonUtils.objectToJson(user));
 //设置session过期时间
 jedisCluster.expire(USER_TOKEN_KEY + ":" + token, SESSION_EXPIRE_TIME);
 return TaotaoResult.ok(token);
}

Other subsystems login, request SSO (log) log, the returned token writes the Cookie , Cookie put the belt next visit:

public TaotaoResult login(String username, String password, 
 HttpServletRequest request, HttpServletResponse response) {
 //请求参数
 Map<String, String> param = new HashMap<>();
 param.put("username", username);
 param.put("password", password);
 //登录处理
 String stringResult = HttpClientUtil.doPost(REGISTER_USER_URL + USER_LOGIN_URL, param);
 TaotaoResult result = TaotaoResult.format(stringResult);
 //登录出错
 if (result.getStatus() != 200) {
 return result;
 }
 //登录成功后把取token信息,并写入cookie
 String token = (String) result.getData();
 //写入cookie
 CookieUtils.setCookie(request, response, "TT_TOKEN", token);
 //返回成功
 return result;
}

 

to sum up:

  • SSO system generates a token, and user information is stored into the Redis, and set an expiration time
  • Other system requests the SSO system log, get token SSO return, writes the Cookie
  • Each request, Cookie will bring, to give interceptor token, if judged to have been logged

Here, in fact, we will find that in fact two changes:

  • The landing is a function of the extraction system (SSO), other systems SSO login request
  • User information would have been saved to the Session, will now be stored user information to Redis

 

3.2 Cookie cross-domain issues

Above we can not solve the Session sharing problem, but in fact there is another problem. Cookie is not across domains

For example, we request http://www.ibixue.com/ , the browser will automatically ibixue.com the Cookie with the past to google servers, and without the http://www.gookang.com of Cookie with over to google server.

This means that, due to the different domain name when the user logs on to the system A, system A return to the browser Cookie, then the user will not request system B system A Cookie with the past.

Cookie exist for cross-domain problem, there are several solutions:

  1. After the server will write the client Cookie, Cookie client to parse the Token parsed, then the Token Request regarded put on the line
  2. Multiple domain names sharing Cookie, Cookie's domain settings wrote in a client's time.
  3. The Token is stored in SessionStroage in (do not rely Cookie will be no cross-domain problems)

Here, we can already achieve single sign-up.

3.3 CAS principle

Speaking of single sign-on, you will definitely see this term: CAS (Central Authentication Service), the following CAS talk about is how you do.

If you have a separate login drawn out into a system , we can play that game. Now we have two systems, namely www.ibixue.com and www.gookang.com, a www.ruanally.com

First, the user wants to access the system A www.ibixue.com limited resources (such as shopping cart functionality, the cart feature requires login to access), system A www.ibixue.com found that users do not log in, then redirects sso to the certification center, and its address as an argument . Address request is as follows:

  • www.ruanally.com?service=www.ibixue.com

sso Certification Center finds that the user is not logged in, will guide the user to the login page, users enter a user name and password, user authentication center and the establishment of a global session (generates a Token, writes the Cookie stored on the browser)

What is single sign-on (SSO)?  Single sign-on (SSO) in the end what does that mean?  [Examples] Demo logic attachment
What is single sign-on (SSO)? Single sign-on (SSO) in the end what does that mean? [Examples] Demo logic attachment

Subsequently, the authentication center redirected back to the system A , and the Token carry over to the system A, redirect the following address:

  • www.ibixue.com?token=xxxxxxx

Next, the system sso A certification center to verify that the Token is correct, if correct, the system A and users to establish a local session ( created the Session ). This system A and the user is already logged a.

What is single sign-on (SSO)?  Single sign-on (SSO) in the end what does that mean?  [Examples] Demo logic attachment
What is single sign-on (SSO)? Single sign-on (SSO) in the end what does that mean? [Examples] Demo logic attachment

 

At this point, the user wants to access the system B  www.gookang.com resource-constrained (such as an order function, after the order feature requires login to access), system B www.gookang.com found that users do not login, then redirected to sso certification Center, and his address as an argument . Address request is as follows:

  • www.ruanally.com?service=www.gookang.com

Note that since before the user with an authentication center www.ruanally.com has established a global session (Cookie was already saved on the browser), so this system B redirected to the authentication center can bring www.ruanally.com Cookie's.

Certification Center according to Cookie brought over discovery has established a global session with the user, and Certification Center redirected back to the system B , and the Token carry over to System B, redirect the following address:

  • www.gookang.com?token=xxxxxxx

Then, go to System B sso Certification Center to verify this Token is correct, if correct, then the system B and users to establish a local session ( created the Session ). This, System B and the user is already logged in.

title

 

See here, in fact, SSO authentication center is similar to a transit station .

Section editor: Soft Alliance Network  

 

 

 

 

Guess you like

Origin blog.csdn.net/cnpinpai/article/details/90669587