Table of Contents
1. Specific implementation steps
2. Code display
Backend code
The front-end code
欢迎来到登录页面
登录成功
Effect display
Home Java javaTutorial How to implement SpringBoot single sign-on

How to implement SpringBoot single sign-on

May 25, 2023 am 11:43 AM
springboot

1. Specific implementation steps

Add an interceptor, set UUID as a unique identifier, and store it in the database

Query through the account of the current login

If the current If the UUID value stored in the user's session is the same as the UUID value in our database, pass

Otherwise, return false, indicating that the user has logged in on another device or browser

2. Code display

First we create a new Spring project

Add the following dependencies

How to implement SpringBoot single sign-on

yml configuration file

server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306 /userdb?characterEncoding=utf-8&&severTimezone=utc
username: root
password: root
thymeleaf:
mode: HTML5
cache: false
suffix: .html
prefix : classpath:/templates/
mybatis:
Mapper-locations: classpath:/mapper/*.xml #Introduce mapper files
type-aliases-package: com.bdqn.springsso.pojo #Introduce type aliases

pom.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.bdqn</groupId>
    <artifactId>springsso</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springsso</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
Copy after login

Backend code

Create the following packages in the java directory, and create the mapper package in resources

How to implement SpringBoot single sign-on

First write the pojo layer entity class User

Note: When creating a table in MySQL, the data type of uuid is varchar, and the length must be larger, otherwise it will run Report an error

package com.bdqn.springsso.pojo;
import lombok.Data;
@Data
public class User {
    //用户id
    private Integer id;
    //账户
    private String username;
    //密码
    private String password;
    //uuid
    private String uuid;
}
Copy after login

Then write the mapper layer UserMapper interface

package com.bdqn.springsso.mapper;
import com.bdqn.springsso.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserMapper {
    //根据姓名和密码查询
    User chekLogin(@Param("username") String username, @Param("password") String password);
    //根据姓名修改uuid
    void update(@Param("uuid") String uuid,@Param("username") String username);
    //根据姓名查询uuid
    String getUUID(@Param("username") String username);
}
Copy after login

Then write the service layer UserService and UserServiceImpl

package com.bdqn.springsso.service;
import com.bdqn.springsso.pojo.User;
public interface UserService {
    //根据姓名和密码查询
    User chekLogin(String username, String password);
    //根据姓名修改uuid
    void update(String uuid,String username);
}
Copy after login
package com.bdqn.springsso.service;
import com.bdqn.springsso.mapper.UserMapper;
import com.bdqn.springsso.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User chekLogin(String username, String password) {
        return userMapper.chekLogin(username,password);
    }
    @Override
    public void update(String uuid,String username) {
        userMapper.update(uuid,username);
    }
}
Copy after login

Then write the interceptor layer UserInterceptor interceptor

package com.bdqn.springsso.interceptor;
import com.bdqn.springsso.mapper.UserMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class UserInterceptor implements HandlerInterceptor {
    private UserMapper userMapper;
    public UserInterceptor(UserMapper userMapper){
        this.userMapper=userMapper;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        //数据库
        String UUID=userMapper.getUUID(username);
        //session
        String uuid = (String)session.getAttribute("uuid");
        System.out.println("uuid = " + uuid);
        System.out.println("UUID = " + UUID);
        if(UUID.equals(uuid)){
            return true;
        }else  {
            System.out.println("拦截"+request.getRequestURI());
            response.sendRedirect("/login");
            response.setStatus(401);
            return false;
        }
    }
}
Copy after login

Then the controller layer UserController

package com.bdqn.springsso.controller;
import com.bdqn.springsso.pojo.User;
import com.bdqn.springsso.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.UUID;
@Controller
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    //登录
    @RequestMapping("/")
    public String goLogin(){
        return "login";
    }
    //登录验证
    @RequestMapping("/login")
    public String chekLogin(String username, String password, HttpSession session){
        User user=userService.chekLogin(username,password);
        if (user==null){
            return  "login";
        }else {
            session.setAttribute("username",username);
            String uuid= UUID.randomUUID().toString().replace("-", "");
            System.out.println("uuid = " + uuid);
            userService.update(uuid,username);
            session.setAttribute("uuid",uuid);
            return "index";
        }
    }
    //测试
    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        return "成功";
    }
}
Copy after login

Then the writing of the config layer MvcConfig

package com.bdqn.springsso.config;
import com.bdqn.springsso.interceptor.UserInterceptor;
import com.bdqn.springsso.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加拦截器,排除/路径和 /login路径
        registry.addInterceptor(new UserInterceptor(userMapper))
                .excludePathPatterns("/","/login");
    }
}
Copy after login

The last is the writing of userMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bdqn.springsso.mapper.UserMapper">
    <update id="update">
        update user set uuid=#{uuid} where username=#{username}
    </update>
    <select id="chekLogin" resultType="com.bdqn.springsso.pojo.User">
        select * from user where username=#{username} and password=#{password}
    </select>
    <select id="getUUID" resultType="java.lang.String">
        select uuid from user where username=#{username}
    </select>
</mapper>
Copy after login

The front-end code

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Login Module</title>
</head>
<body>
<h2 id="欢迎来到登录页面">欢迎来到登录页面</h2>
<form  th:action="@{/login}" method="post">
  用户:<input type="text" name="username"><br>
  密码:<input type="password" name="password"><br>
  <button type="submit">登录</button>
</form>
</body>
</html>
Copy after login

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2 id="登录成功">登录成功</h2>
<a th:href="@{/test}" rel="external nofollow" >测试</a>
</body>
</html>
Copy after login

Effect display

First we use Firefox browser to operate

Enter http:// localhost:8080/Enter the login page

How to implement SpringBoot single sign-on

##Click to log in

How to implement SpringBoot single sign-on

Click to test

How to implement SpringBoot single sign-on

Then we return to the login success page

Use Google Chrome to enter http://localhost:8080/ to log in

How to implement SpringBoot single sign-on

After logging in, you will enter the login success page

How to implement SpringBoot single sign-on

At this time we return to the Firefox browser

Click the test hyperlink to find that the page jumps to the login page

Indicates that the single sign-on test was successful

How to implement SpringBoot single sign-on

The above is the detailed content of How to implement SpringBoot single sign-on. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

See all articles