Springboot + mybatis Plus + springsecurity + JWT implements user stateless request authentication (front and back end separation)

On the road of struggle 2021-11-25 18:37:17
springboot mybatis springsecurity jwt implements

1、 Basic technical framework

Technical name edition
SpringBoot 2.1.9.RELEASE
MyBatis-plus 3.3.1
MySQL 8.0.11
SpringSecurity 5.1.6.RELEASE
jjwt 0.9.0
lombok 1.18.10
guava 30.1.1-jre
hutool-all 5.5.2
druid 1.2.3
swagger3 3.0
aop 1.9.4
fastjson 1.2.47

2、 complete pom.xml 

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zzg</groupId>
<artifactId>Meta</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Integrate Mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!-- Integrate MySQL Drive pack -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- Integrate SpringSecurity Security framework -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Integrate JWT-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<!-- Integrate lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Integrate guava tool kit -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1.1-jre</version>
</dependency>
<!-- Integrate hutool-all tool kit -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.2</version>
</dependency>
<!--druid Database connection pool -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<!-- swagger3 Interface document generator -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
<exclusions>
<exclusion>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-metadata</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-metadata</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<!-- Integrate SpringAop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- Integrate Alibaba fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</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>

3、 Initialization script

/*
Navicat MySQL Data Transfer
Source Server : 192.168.1.73
Source Server Type : MySQL
Source Server Version : 80015
Source Host : 192.168.1.73:3306
Source Schema : banan_test
Target Server Type : MySQL
Target Server Version : 80015
File Encoding : 65001
Date: 05/11/2021 19:14:17
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_sys_auth
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_auth`;
CREATE TABLE `t_sys_auth` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`auth_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT ' Permission to name ',
`permission` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT ' Authority sign ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = ' System permissions ' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_sys_auth
-- ----------------------------
INSERT INTO `t_sys_auth` VALUES (1, ' Edit permissions of system users ', 'sys:user:edit');
INSERT INTO `t_sys_auth` VALUES (2, ' System user query authority ', 'sys:user:view');
INSERT INTO `t_sys_auth` VALUES (3, ' System role editing permission ', 'sys:role:edit');
INSERT INTO `t_sys_auth` VALUES (4, ' System role query permission ', 'sys:role:view');
INSERT INTO `t_sys_auth` VALUES (5, ' System permission edit permission ', 'sys:auth:edit');
INSERT INTO `t_sys_auth` VALUES (6, ' System permission query permission ', 'sys:auth:view');
INSERT INTO `t_sys_auth` VALUES (7, ' System log editing permission ', 'sys:log:edit');
INSERT INTO `t_sys_auth` VALUES (8, ' System log query permission ', 'sys:log:view');
-- ----------------------------
-- Table structure for t_sys_log
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_log`;
CREATE TABLE `t_sys_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`method` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT ' Request method ',
`uri` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT ' Request address ',
`params` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT ' Request parameters ',
`time` bigint(10) NULL DEFAULT NULL COMMENT ' Request time ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_sys_log
-- ----------------------------
INSERT INTO `t_sys_log` VALUES (2, 'GET', '/log/listData', 'page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (3, 'GET', '/log/list', '', 0);
INSERT INTO `t_sys_log` VALUES (4, 'GET', '/log/listData', 'page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (5, 'GET', '/log/listData', 'page=1&limit=10&id=2', 0);
INSERT INTO `t_sys_log` VALUES (6, 'GET', '/log/listData', 'page=1&limit=10&id=', -1);
INSERT INTO `t_sys_log` VALUES (7, 'POST', '/log/delete', '[{\"id\":1}]', 0);
INSERT INTO `t_sys_log` VALUES (8, 'GET', '/log/listData', 'page=1&limit=10&id=', 0);
INSERT INTO `t_sys_log` VALUES (9, 'GET', '/log/list', '', 0);
INSERT INTO `t_sys_log` VALUES (10, 'GET', '/log/listData', 'page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (11, 'GET', '/log/list', '', 0);
INSERT INTO `t_sys_log` VALUES (12, 'GET', '/log/listData', 'page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (13, 'GET', '/log/list', '', 0);
INSERT INTO `t_sys_log` VALUES (14, 'GET', '/log/listData', 'page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (15, 'GET', '/log/listData', 'page=2&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (16, 'GET', '/auth/list', '', 0);
INSERT INTO `t_sys_log` VALUES (17, 'GET', '/auth/listData', 'page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (18, 'GET', '/auth/bind', 'id=1', 0);
INSERT INTO `t_sys_log` VALUES (19, 'GET', '/auth/roleListData', 'authId=1&page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (20, 'GET', '/auth/list', '', 0);
INSERT INTO `t_sys_log` VALUES (21, 'GET', '/auth/listData', 'page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (22, 'GET', '/log/list', '', 0);
INSERT INTO `t_sys_log` VALUES (23, 'GET', '/log/listData', 'page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (24, 'GET', '/log/listData', 'page=3&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (25, 'GET', '/log/listData', 'page=2&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (26, 'GET', '/auth/list', '', 0);
INSERT INTO `t_sys_log` VALUES (27, 'GET', '/auth/listData', 'page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (28, 'GET', '/log/list', '', 0);
INSERT INTO `t_sys_log` VALUES (29, 'GET', '/log/listData', 'page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (30, 'GET', '/auth/list', '', -1);
INSERT INTO `t_sys_log` VALUES (31, 'GET', '/auth/listData', 'page=1&limit=10', 0);
INSERT INTO `t_sys_log` VALUES (32, 'GET', '/log/list', '', 0);
INSERT INTO `t_sys_log` VALUES (33, 'GET', '/log/listData', 'page=1&limit=10', 0);
-- ----------------------------
-- Table structure for t_sys_role
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_role`;
CREATE TABLE `t_sys_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`role_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT ' Character name ',
`role_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT ' Character encoding ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = ' System roles ' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_sys_role
-- ----------------------------
INSERT INTO `t_sys_role` VALUES (1, ' Ordinary employees ', 'USER');
INSERT INTO `t_sys_role` VALUES (2, ' project manager ', 'PM');
-- ----------------------------
-- Table structure for t_sys_role_auth
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_role_auth`;
CREATE TABLE `t_sys_role_auth` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`role_id` bigint(20) NULL DEFAULT NULL COMMENT ' role ID',
`auth_id` bigint(20) NULL DEFAULT NULL COMMENT ' jurisdiction ID',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = ' Role permission relationship ' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_sys_role_auth
-- ----------------------------
INSERT INTO `t_sys_role_auth` VALUES (1, 2, 1);
INSERT INTO `t_sys_role_auth` VALUES (2, 1, 2);
INSERT INTO `t_sys_role_auth` VALUES (3, 2, 2);
INSERT INTO `t_sys_role_auth` VALUES (4, 2, 3);
INSERT INTO `t_sys_role_auth` VALUES (5, 1, 4);
INSERT INTO `t_sys_role_auth` VALUES (6, 2, 4);
INSERT INTO `t_sys_role_auth` VALUES (7, 2, 5);
INSERT INTO `t_sys_role_auth` VALUES (8, 1, 6);
INSERT INTO `t_sys_role_auth` VALUES (9, 2, 6);
INSERT INTO `t_sys_role_auth` VALUES (10, 2, 7);
INSERT INTO `t_sys_role_auth` VALUES (11, 2, 8);
-- ----------------------------
-- Table structure for t_sys_user
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_user`;
CREATE TABLE `t_sys_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT ' User name ',
`nickname` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT ' The user nickname ',
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT ' User password ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = ' System users ' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_sys_user
-- ----------------------------
INSERT INTO `t_sys_user` VALUES (1, 'user', 'C3Stones', '$2a$10$RFjGxPxq8EZokh89z.DcIeSpBJHfeRozfXUZSHnfN14bb94JKVRia');
INSERT INTO `t_sys_user` VALUES (2, 'system', ' Administrators ', '$2a$10$RFjGxPxq8EZokh89z.DcIeSpBJHfeRozfXUZSHnfN14bb94JKVRia');
-- ----------------------------
-- Table structure for t_sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `t_sys_user_role`;
CREATE TABLE `t_sys_user_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_id` bigint(20) NULL DEFAULT NULL COMMENT ' user ID',
`role_id` bigint(20) NULL DEFAULT NULL COMMENT ' role ID',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = ' User role relationship ' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_sys_user_role
-- ----------------------------
INSERT INTO `t_sys_user_role` VALUES (1, 1, 1);
INSERT INTO `t_sys_user_role` VALUES (2, 2, 2);
SET FOREIGN_KEY_CHECKS = 1;

4、 Screenshot of project structure :

 5、springsecurity handler Definition

package com.zzg.security.handler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.zzg.common.vo.Response;
import cn.hutool.http.HttpStatus;
/**
* No permission to handle class
*
* @author zzg
*
*/
@Component
public class UserAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException {
Response<String> responseBody = Response.error(HttpStatus.HTTP_UNAUTHORIZED, "Unauthorized", " User not authenticated ");
response.getWriter().write(JSON.toJSONString(responseBody));
}
}
package com.zzg.security.handler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.zzg.common.vo.Response;
import cn.hutool.http.HttpStatus;
/**
* Login failure processing class
*
* @author zzg
*
*/
@Component
public class UserLoginFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException {
Response<String> responseBody = Response.error(HttpStatus.HTTP_BAD_REQUEST, "Bad Request", " request was aborted ");
response.getWriter().write(JSON.toJSONString(responseBody));
}
}
package com.zzg.security.handler;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.zzg.common.vo.Response;
import com.zzg.security.entity.UserDetails;
import com.zzg.security.jwt.JwtTokenUtil;
import cn.hutool.http.HttpStatus;
/**
* Login successfully processed class
*
* @author zzg
*
*/
@Component
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
Map<String, Object> paramter = new HashMap<String, Object>();
paramter.put("username", userDetails.getUsername());
String jwtToken = JwtTokenUtil.createToken(paramter);
Response<String> responseBody = Response.error(HttpStatus.HTTP_OK, "Login Success", jwtToken);
response.getWriter().write(JSON.toJSONString(responseBody));
}
}
package com.zzg.security.handler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.zzg.common.vo.Response;
import cn.hutool.http.HttpStatus;
/**
* Logout successfully processed class
*
* @author zzg
*
*/
@Component
public class UserLogoutSuccessHandler implements LogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException {
Response<String> responseBody = Response.error(HttpStatus.HTTP_OK, "Logout Success", " User exit succeeded ");
response.getWriter().write(JSON.toJSONString(responseBody));
}
}
package com.zzg.security.handler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.zzg.common.vo.Response;
import cn.hutool.http.HttpStatus;
/**
* Processing class not logged in
*
* @author zzg
*
*/
@Component
public class UserNotLoginHandler implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
Response<String> responseBody = Response.error(HttpStatus.HTTP_UNAUTHORIZED, "Unauthorized", " User not authenticated ");
response.getWriter().write(JSON.toJSONString(responseBody));
}
}

6、springsecurity UserDetails Definition

package com.zzg.security.entity;
import java.io.Serializable;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import com.zzg.sys.entity.User;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* System user details
*
* @author zzg
*
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class UserDetails extends User
implements org.springframework.security.core.userdetails.UserDetails, Serializable {
private static final long serialVersionUID = 1L;
/**
* User roles
*/
private Collection<GrantedAuthority> authorities;
/**
* Whether the account has expired
*/
private boolean isAccountNonExpired = false;
/**
* Is the account locked
*/
private boolean isAccountNonLocked = false;
/**
* Does the certificate expire
*/
private boolean isCredentialsNonExpired = false;
/**
* Whether the account is valid
*/
private boolean isEnabled = true;
/**
* Obtain user rights
*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
/**
* Determine whether the account expires
*/
@Override
public boolean isAccountNonExpired() {
return isAccountNonExpired;
}
/**
* Determine whether the account is locked
*/
@Override
public boolean isAccountNonLocked() {
return isAccountNonLocked;
}
/**
* Judge whether the certificate is expired
*/
@Override
public boolean isCredentialsNonExpired() {
return isCredentialsNonExpired;
}
/**
* Determine whether the account number is valid
*/
@Override
public boolean isEnabled() {
return isEnabled;
}
}

7、springsecurity UserDetailsService Definition

package com.zzg.security.service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzg.security.entity.UserDetails;
import com.zzg.sys.entity.Role;
import com.zzg.sys.entity.User;
import com.zzg.sys.service.RoleService;
import com.zzg.sys.service.UserService;
/**
* The user login Service
*
* @author zzg
*
*/
@Service
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
/**
* Check the user information according to the user name
*
* @param username User name
* @return User details
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("username", username);
User user = userService.getOne(queryWrapper);
if (user != null) {
UserDetails userDetails = new UserDetails();
BeanUtils.copyProperties(user, userDetails);
// User roles
Set<GrantedAuthority> authorities = new HashSet<>();
// Query user roles
List<Role> roleList = roleService.findByUserId(userDetails.getId());
roleList.forEach(role -> {
authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleCode()));
});
userDetails.setAuthorities(authorities);
return userDetails;
}
return null;
}
}

8、springsecurity AuthenticationProvider Definition

package com.zzg.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import com.zzg.security.entity.UserDetails;
import com.zzg.security.service.UserDetailsService;
import cn.hutool.core.util.StrUtil;
/**
* User login authentication processing class
*
* @author zzg
*
*/
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserDetailsService userDetailsService;
/**
* Authentication
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// Get username
String username = (String) authentication.getPrincipal();
// Get password
String password = (String) authentication.getCredentials();
UserDetails userDetails = (UserDetails) userDetailsService.loadUserByUsername(username);
if (userDetails == null) {
throw new UsernameNotFoundException(" The username does not exist ");
}
if (!StrUtil.equals(username, userDetails.getUsername())
|| !new BCryptPasswordEncoder().matches(password, userDetails.getPassword())) {
throw new BadCredentialsException(" Wrong user name or password ");
}
return new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
}
/**
* Supports specified authentication
*/
@Override
public boolean supports(Class<?> authentication) {
return true;
}
}

9. jwt Tool class definition

package com.zzg.security.jwt;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
public class JwtTokenUtil {
/** secret key secret */
private static String secret = "meta";
/** Expiration time , The unit is in seconds */
private static long expire = 7 * 24 * 60 * 60;
/**
* analysis token
*
* @param jsonWebToken
* @return
*/
public static Claims parseToken(String token) {
Claims claims = null;
try {
claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
} catch (Exception e) {
return claims;
}
return claims;
}
/**
* newly build token
*
* @param audience
* @param issuer
*
* @return
*/
public static String createToken(Map<String, Object> paramter) {
if (Objects.isNull(paramter)) {
paramter = new HashMap<>();
}
// Expiration time
Date expireDate = new Date(System.currentTimeMillis() + expire * 1000);
return Jwts.builder().setHeaderParam("typ", "JWT") // Set header information
.setClaims(paramter) // Load custom user information
.setExpiration(expireDate) // token Expiration time
.signWith(SignatureAlgorithm.HS512, secret) // secret key
.compact();
}
/**
* Refresh token
*
* @param audience
* @param issuer
*
* @return
*/
public static String referToken(Map<String, Object> paramter) {
if (Objects.isNull(paramter)) {
paramter = new HashMap<>();
}
// Expiration time
Date expireDate = new Date(System.currentTimeMillis() + expire * 1000);
return Jwts.builder().setHeaderParam("typ", "JWT") // Set header information
.setClaims(paramter) // Load custom user information
.setExpiration(expireDate) // token Expiration time
.signWith(SignatureAlgorithm.HS512, secret) // secret key
.compact();
}
}

10.jwt Credential validation interceptor

package com.zzg.security.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.zzg.security.entity.UserDetails;
import com.zzg.security.jwt.JwtTokenUtil;
import com.zzg.security.service.UserDetailsService;
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Autowired
UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer")) {
final String authToken = authHeader.substring("Bearer".length());
String username = (String) JwtTokenUtil.parseToken(authToken).get("username");
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (userDetails != null) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
}
chain.doFilter(request, response);
}
}

11、springsecurity Configuration object

package com.zzg.security.conf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.zzg.security.UserAuthenticationProvider;
import com.zzg.security.filter.JwtAuthenticationTokenFilter;
import com.zzg.security.handler.UserAccessDeniedHandler;
import com.zzg.security.handler.UserLoginFailureHandler;
import com.zzg.security.handler.UserLoginSuccessHandler;
import com.zzg.security.handler.UserLogoutSuccessHandler;
import com.zzg.security.handler.UserNotLoginHandler;
/**
* System security core configuration
*
* @author zzg
*
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
public static final Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
/**
* No permission to handle class
*/
@Autowired
private UserAccessDeniedHandler userAccessDeniedHandler;
/**
* The user is not logged in to the processing class
*/
@Autowired
private UserNotLoginHandler userNotLoginHandler;
/**
* The user successfully logged in and processed the class
*/
@Autowired
private UserLoginSuccessHandler userLoginSuccessHandler;
/**
* User login failure processing class
*/
@Autowired
private UserLoginFailureHandler userLoginFailureHandler;
/**
* The user successfully logged out of the processing class
*/
@Autowired
private UserLogoutSuccessHandler userLogoutSuccessHandler;
/**
* User login authentication
*/
@Autowired
private UserAuthenticationProvider userAuthenticationProvider;
/**
* jwt Interceptor
*/
@Autowired
JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
/**
* encryption
*
* @return
*/
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* User login authentication
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(userAuthenticationProvider);
}
/**
* Security permission configuration
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// Get rid of CSRF
http.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // Use JWT, close token
.and()
.httpBasic().authenticationEntryPoint(userNotLoginHandler)
.and()
.authorizeRequests()
// .anyRequest()
// .access("@rbacauthorityservice.hasPermission(request,authentication)") // RBAC dynamic url authentication
.and()
.formLogin() // Open login
.successHandler(userLoginSuccessHandler) // Login successful
.failureHandler(userLoginFailureHandler) // Login failed
.permitAll()
.and()
.logout()
.logoutSuccessHandler(userLogoutSuccessHandler)
.permitAll();
http.exceptionHandling().accessDeniedHandler(userAccessDeniedHandler); // No access JSON Formatted data
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); // JWT Filter
}
}

12、PostMan Screenshot of simulated front and rear end separation effect

 

 13、 Project source code

版权声明
本文为[On the road of struggle]所创,转载请带上原文链接,感谢
https://javamana.com/2021/11/20211109101904483C.html

  1. Flink Handling Function Real War II: processfunction class, Java thread interview subject
  2. Oracle SQL injection summary
  3. [Java data structure] you must master the classic example of linked list interview (with super detailed illustration and code)
  4. Record a java reference passing problem
  5. spring JTA 關於异常處理的時機問題
  6. Java - Set - Map (double file) - dija Rewriting, 2021 Java Developer's Performance Optimization
  7. Android入门教程 | OkHttp + Retrofit 取消请求的方法
  8. Java 8 Stream API and common methods, Java Junior Program interview
  9. Github 疯传!史上最强!BAT 大佬,2021年最新Java大厂面试笔试题分享
  10. git(3)Git 分支,zookeeper下载教程
  11. Java Backend Internet 500 questions d'entrevue moyennes et avancées (y compris les réponses), technologie de crochet Linux
  12. Entretien d'entretien d'usine Java post sprint de 100 jours - accumulation de jours et de mois, trois questions par jour [jour 12, fonction de principe de Zookeeper
  13. Tutoriel Java - reflection, tutoriel de téléchargement mongodb
  14. How to analyze several common key and hot issues in redis from multiple dimensions
  15. GIT (3) GIT Branch, Zookeeper Download tutoriel
  16. Tutoriel de démarrage Android | okhttp + Retrofit comment annuler une demande
  17. Design pattern [3.3] - Interpretation of cglib dynamic agent source code
  18. Share the actual operation of private collection project nodejs backend + Vue + Mysql to build a management system
  19. Springboot has 44 application initiators
  20. GitHub上霸榜久居不下的《Java面试突击宝典》,java图形用户界面设计基础
  21. GitHub上访问下载破百万的神仙文档《Java面试神技》看完我呆了,java面试问项目中遇到的问题
  22. GitHub上标星75k 超牛的《Java面试突击版,java高级工程师技能
  23. GitHub上标星2,java项目开发实训教程
  24. Docker development environment Preview
  25. JavaScript高級深入淺出:掌握 this 指向
  26. JavaScript Advanced Insight and outside: Mastering this direction
  27. Vue de l'application pratique de Javascript, drop drag Event
  28. docker 安装部署 Jenkins 2.322
  29. kafka安装
  30. 近九万字图文详解RabbitMQ
  31. Engaged in Java for one and a half years, how to break through yourself
  32. 输出9*9乘法表----java
  33. 判断一个数是不是素数-------java
  34. java项目,记录页面修改值,内部打“官司”用
  35. Docker installation Deployment Jenkins 2.322
  36. Comment porter un pantalon en hiver? Les petits hommes, les jambes épaisses et la largeur de l'entrejambe peuvent être vus. 3 techniques pour éviter la foudre
  37. MySQL下载和安装教程
  38. In depth analysis of rocketmq source code - message storage module
  39. Spring transaction management
  40. mysql恢复ibd数据,为何频频报错?
  41. [skills with annual salary of 60W] after working for 5 years, do you really understand netty and why to use it? (deep dry goods)
  42. Pourquoi MySQL récupère - t - il fréquemment les données ibd?
  43. Tutoriels de téléchargement et d'installation MySQL
  44. In IntelliJ idea, develop a fishing and reading plug-in
  45. Talk about how to integrate SPI with spring
  46. 重学Spring系列之Swagger2.0和Swagger3.0
  47. Hadoop05【命令操作】,Java400道面试题通关宝典助你进大厂
  48. Guava Cache缓存设计原理,java基础入门
  49. Gson:GitHub 标星 18K 的 JSON 解析器,Google 出品的 Java JSON 解析器
  50. gRPC学习之六:gRPC-Gateway集成swagger,java语言程序设计与数据结构进阶版
  51. Projet Java, enregistrer la valeur de modification de la page, utilisé pour les litiges internes
  52. Déterminer si un nombre est un nombre premier - - Java
  53. Sortie 9 * 9 tableau de multiplication - Java
  54. Plusieurs façons de réinitialiser le déplacement du Groupe de consommateurs Kafka
  55. GRPC Learning six: GRPC Gateway Integrated Swagger, Java language programming and data structure Advanced Edition
  56. python数据结构:数组、列表、栈、队列及实现
  57. Gson: json Parser for github Star 18k, Java json Parser from Google
  58. Principes de conception du cache Guava, Introduction à la base Java
  59. Un pantalon beige = élégant, blanc + haut de gamme, si beau cet hiver!
  60. Hadoop05 【 commande 】, Java 400 questions d'entrevue pour vous aider à entrer dans l'usine