当前位置:网站首页>Easy to master SSO single sign on, see this article
Easy to master SSO single sign on, see this article
2022-07-25 01:51:00 【Code Icee】
One 、 introduction
as everyone knows , A web system , The most basic function is login , As a JAVA The programmer , From write down Hello Word In the process of becoming a technological bull , Login function is not necessarily the most written , But it must be the most common , This article briefly introduces SSO The concept and principle of , And then use SpringBoot A simple SSO System . System use token In the form of , rely on cookie carry token towards sso The server validates , Allow access to the requested address after verification .
Two 、SSO Introduce
as everyone knows , When we first started writing business , There may be only one module , But as the development time increases , There will be more and more code , It will be very redundant , Then at this time, we will split the code into small modules one after another , Every module is a system , For example, we have built an e-commerce system , He has a shopping cart system , Commodity system , Purchase system, etc , Then after we log in , When accessing another system , If you want to log in again , It will be very troublesome , So here we introduce SSO Single sign on System , As long as a system logs in successfully , The other system doesn't need to log in .
3、 ... and 、 Common examples
The e-commerce we use most in our daily life APP It's probably Taobao , Here we use Taobao as an example
First , We log into the main interface of Taobao , And log in
Click to jump to Taobao main interface

ad locum , We can see the domain name of Taobao ,taobao.com, This is the time , Let's take a look at the shopping cart , We will find that , After entering the shopping cart menu , The domain name of the website has changed 
that , We can know , ad locum , Single sign on occurs , As long as we log in to the main interface , Accessing other systems , Like a shopping cart , Favorites , We are also logged in , Then there is no need to do it again , This saves a lot of things , So today we will learn how to do this .
3、 ... and 、SSO Code implementation
At present, there are two common login , One is to store user information session in , Judge when the mirror is operating session Whether there is , Another is through token To judge . We know session It's not shared , that , Can we put token There is cookie in , When a system logs in , When accessing another system , Let's judge token Whether it is right , If correct , Just let it go , error , The intercept , Here we simply implement
Assign a domain name to this machine
Before you write the code , We need to assign a domain name to our host first , This will facilitate our next work
Let's check our LAN first ip

Turn on my computer , Find this path :C:\Windows\System32\drivers\etc

Then open the host file , Compiling , The domain name can be chosen by yourself , Save and exit after finishing

Write code
We need two services to simulate , So we first set up the following two files , And then to client Set port 8081,server Set up 8082

then , Let's add the rest of the code , First, client Under the
User class
package com.znb.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String password;
}
LoginCacheUtil
package com.znb.utils;
import com.znb.pojo.User;
import java.util.HashMap;
import java.util.Map;
public class LoginCacheUtil {
public static Map<String , User> loginUser = new HashMap<>();
}
LoginController
package com.znb.controller;
import com.znb.pojo.User;
import com.znb.utils.LoginCacheUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@Controller
@RequestMapping("/login")
public class LoginController {
private static Set<User> dbUsers;
static {
dbUsers = new HashSet<>();
dbUsers.add(new User(0,"xiaoyan","000000"));
dbUsers.add(new User(1,"tangsan","000000"));
dbUsers.add(new User(2,"yecheng","000000"));
}
@PostMapping
public String doLogin(User user, HttpSession session, HttpServletResponse response){
// Simulate finding users in the database by logging in user name and password from the database
Optional<User> first = dbUsers.stream().filter(dbUser -> dbUser.getUsername().equals(user.getUsername()) &&
dbUser.getPassword().equals(user.getPassword()))
.findFirst();
// Judge whether the user logs in
if(first.isPresent()){
// Save the user's login information
String token = UUID.randomUUID().toString();
Cookie cookie = new Cookie("TOKEN",token);
cookie.setDomain("codeicee.com");
response.addCookie(cookie);
LoginCacheUtil.loginUser.put(token,first.get());
}
else{
// Login failed
session.setAttribute("msg"," Wrong user name or password ");
return "login";
}
// Redirect to target Address
return "index" ;
}
@GetMapping("info")
@ResponseBody
public ResponseEntity<User> getUserInfo(String token){
if(!StringUtils.isEmpty(token)){
User user = LoginCacheUtil.loginUser.get(token);
return ResponseEntity.ok(user);
}else {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
}
}
ViewController
package com.znb.controller;
import com.znb.pojo.User;
import com.znb.utils.LoginCacheUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
/** * Page Jump logic */
@Controller
@RequestMapping("/view")
public class ViewController {
@RequestMapping("/")
public String index(){
return "index";
}
/** * Go to the login page * @return */
@GetMapping("/login")
public String toLogin(@RequestParam(required = false,defaultValue = "")String target,
HttpSession session,
@CookieValue(required = false,value = "TOKEN")Cookie cookie){
if(StringUtils.isEmpty(target)){
target = "http://www.codeicee.com:8081";
}
// If the logged in user visits the login page again , Need to redirect
if(cookie != null){
//token
String value = cookie.getValue();
User user = LoginCacheUtil.loginUser.get(value);
if(user != null){
return "product";
}
}
// Redirect address
session.setAttribute("target",target);
return "login";
}
}
index
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> home page </h1>
</body>
</html>
login
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title>Login Module</title>
</head>
<body>
<h1> Welcome to the login page </h1>
<p style="color: red;" th:text="${session.msg}"></p>
<form action="/login" method="POST">
user name :<input name="username" value=""/>
password :<input name="password" value=""/>
<button type="submit"> Sign in </button>
</form>
</body>
</html>
product
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> product </h1>
</body>
</html>
And then there was server
ViewController
package com.znb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Controller
@RequestMapping("/view")
public class ViewController {
@Autowired
private RestTemplate restTemplate;
private final String USER_INFO_ADDRESS = "http://codeicee.com:8081/login/info?token=";
@GetMapping("/index")
public String toIndex(@CookieValue(required = false,value = "TOKEN") Cookie cookie,
HttpSession session){
if(cookie != null){
String token = cookie.getValue();
if(!StringUtils.isEmpty(token)){
Map result = restTemplate.getForObject(USER_INFO_ADDRESS + token,Map.class);
session.setAttribute("loginUser",result);
}
}
return "index";
}
}
Start both projects , We will find that , When client After logging in server Your login was also successful
边栏推荐
- Synchronization primitive: lock
- Commonjs export import
- 6-10 vulnerability exploitation SMTP experimental environment construction
- MySQL Basics (concepts, common instructions)
- ES6 modularization
- Create thread: pthread_ create
- Leetcode - number of palindromes
- Peripherals: timer, watchdog and RTC
- Web vulnerability
- Harbor installation
猜你喜欢

Specificity and five applications of Worthington alcohol dehydrogenase

Synchronization primitive: lock

JVM Foundation

Worthington carboxyl transfer carbonic anhydrase application and literature reference

Kubernetes creates a user with dashboard read-only permission (with exec permission)

Redis learning notes (2) - power node of station B

Several schemes of traffic exposure in kubernetes cluster

Fraud detection using CSP
![[leetcode] 3. Longest substring without repeated characters - go language problem solution](/img/63/57d3557d77d44b51b7d0f71669568f.png)
[leetcode] 3. Longest substring without repeated characters - go language problem solution

Luo min cannot become Dong Yuhui
随机推荐
Custom type
[daily question in summer] Luogu p6850 Noi
Academicians said: researchers should also support their families. They can only do short-term and fast research if they are not promoted
Take C language from 0 to 1 - program structure and use examples
ES6 modularization
Green low-carbon Tianyi cloud, a new engine of digital economy!
AWD thinking
Management mode of agricultural science data center based on life cycle theory
An article explains unsupervised learning in images in detail
[recognize cloud Nativity] Chapter 4 cloud network section 4.9.4.3 - smart network card usage scenario - network acceleration implementation
Download files and web pages with WGet
Standard transfer function
G025-db-gs-ins-02 openeuler deployment opengauss (1 active and 1 standby)
Musk responded whether he would upload his brain to the cloud: already did it!
iptables :chains, target
Beijing Zhun electric clock, Beidou clock server, GPS network time server, NTP satellite timing system
Cloud native platform, let edge applications play out!
Guide to the construction of network security testing laboratory - Chapter 1, section 1.5 key terms
If in ython__ name__ == ‘__ main__‘: Function and principle of
Luo min cannot become Dong Yuhui