您现在的位置是:首页 >技术杂谈 >springboot整合security,mybatisPlus,thymeleaf实现登录认证及用户,菜单,角色权限管理网站首页技术杂谈
springboot整合security,mybatisPlus,thymeleaf实现登录认证及用户,菜单,角色权限管理
简介springboot整合security,mybatisPlus,thymeleaf实现登录认证及用户,菜单,角色权限管理
介绍
本系统为springboot整合security,mybatisPlus,thymeleaf实现登录认证及用户,菜单,角色权限管理。页面为极简模式,没有任何渲染。
源码:https://gitee.com/qfp17393120407/spring-boot_thymeleaf
开发步骤
架构截图
pom文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!--参数校验-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.8.Final</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
配置文件
server:
port: 9011
spring:
application:
name: security-test
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/wechat?serverTimezone=Asia/Shanghai&characterEncoding=utf-8
username: root
password: root
启动类
@SpringBootApplication
@EnableOpenApi
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class,args);
}
}
准备建表和实体类
此处以用户表为例,其他表数据可在源码获取。
用户表
CREATE TABLE `user` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL COMMENT '用户名',
`password` varchar(200) NOT NULL COMMENT '密码',
`phone` varchar(20) NOT NULL COMMENT '手机号',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` datetime NOT NULL COMMENT '更新时间',
`create_user` varchar(20) NOT NULL COMMENT '创建用户',
`update_user` varchar(20) NOT NULL COMMENT '更新用户',
`user_type` char(2) DEFAULT '0' COMMENT '用户类型,0-普通用户,1-超级管理员',
`group_id` int DEFAULT NULL COMMENT '分组id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3
共用属性
package com.test.user.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author清梦
* @site www.xiaomage.com
* @company xxx公司
* @create 2023-05-06 15:11
*/
@Data
public abstract class AbstractEntity implements Serializable {
@TableId(type = IdType.AUTO)
private Integer id;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
@TableField(fill = FieldFill.INSERT)
private String createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateUser;
}
共用属性自动填充配置
package com.test.user.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.test.user.entity.AbstractEntity;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.Objects;
/**
* @author清梦
* @site www.xiaomage.com
* @company xxx公司
* @create 2023-05-09 15:16
*/
@Component
public class DefaultFieldFillHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof AbstractEntity){
AbstractEntity abstractEntity = (AbstractEntity)metaObject.getOriginalObject();
Date now = new Date();
abstractEntity.setCreateTime(now);
abstractEntity.setUpdateTime(now);
String username = getLoginUserName();
abstractEntity.setCreateUser(username);
abstractEntity.setUpdateUser(username);
}
}
@Override
public void updateFill(MetaObject metaObject) {
Object updateTime = getFieldValByName("updateTime", metaObject);
if (Objects.isNull(updateTime)){
setFieldValByName("updateTime",new Date(),metaObject);
}
Object updateUser = getFieldValByName("updateUser", metaObject);
if (Objects.isNull(updateUser)){
setFieldValByName("updateUser",getLoginUserName(),metaObject);
}
}
public String getLoginUserName(){
String username = "anonymous";
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)){
username = authentication.getName();
}
return username;
}
}
实体类
package com.test.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
/**
* @author清梦
* @site www.xiaomage.com
* @company xxx公司
* @create 2023-05-06 10:06
*/
@Data
@TableName("user")
public class User extends AbstractEntity{
@NotBlank(message = "请输入用户名")
@Length(message = "不能超过 {max} 个字符",max = 20)
private String username;
@NotBlank(message = "请输入密码")
@Length(message = "最少为{min}个字符",min = 6)
private String password;
@NotBlank(message = "请输入手机号")
@Pattern(regexp = "^1[34578][0-9]{9}$",message = "请输入正确的手机号")
private String phone;
private Integer groupId;
private String userType;
}
security配置
package com.test.user.config;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.annotation.Resource;
/**
* @author清梦
* @site www.xiaomage.com
* @company xxx公司
* @create 2023-05-06 15:15
*/
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private UserDetailsService userDetailsService;
@Bean
PasswordEncoder getPasswordEncoder(){
return new BCryptPasswordEncoder();
}
//security的鉴权排除列表
private static final String [] excludeAuthPages = {
"/user/login",
"/login"
};
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers(excludeAuthPages).permitAll()
.anyRequest().permitAll()
.and().formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.and().exceptionHandling()
.accessDeniedPage("/403.html")
.and()
.logout()
.invalidateHttpSession(true)
.deleteCookies()
.clearAuthentication(true)
.logoutSuccessUrl("/login.html");
}
}
实现UserDetailsService接口的loadUserByUsername方法
这个方法具体实现在用户实现类中,具体代码在用户实现类中给出
用户接口
package com.test.user.controller;
import com.test.user.entity.User;
import com.test.user.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author清梦
* @site www.xiaomage.com
* @company xxx公司
* @create 2023-05-06 14:35
*/
@Api(tags = "用户管理")
@Controller
public class UserController {
@Autowired
UserService userService;
@Autowired
PasswordEncoder passwordEncoder;
@PreAuthorize("hasAnyAuthority('user:select')")
@RequestMapping("/toUserList")
public String toUserList(Model model){
List<User> userList = userService.getUserList();
model.addAttribute("userList",userList);
return "userList";
}
@PreAuthorize("hasAnyAuthority('user:save')")
@RequestMapping("/toAddUser")
public String toSave(){
return "addUser";
}
@PreAuthorize("hasAnyAuthority('user:save')")
@RequestMapping("/addUser")
public String save(User user){
String password = user.getPassword();
user.setPassword(passwordEncoder.encode(password));
userService.saveOrUpdate(user);
return "redirect:/toUserList";
}
@PreAuthorize("hasAnyAuthority('user:save')")
@RequestMapping("/toEditUser")
public String toUpdateUser(Integer id,Model model) {
User user=userService.getById(id);
System.out.println("id="+user.getId());
model.addAttribute("user",user);
return "updateUser";
}
@PreAuthorize("hasAnyAuthority('user:save')")
@RequestMapping("/updateUser")
public String updateUser(User user) {
userService.saveOrUpdate(user);
return "redirect:/toUserList";
}
@PreAuthorize("hasAnyAuthority('user:delete')")
@RequestMapping("/delete")
public String delete(Integer id){
userService.delete(id);
return "redirect:/toUserList";
}
}
mapper
package com.test.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.test.user.entity.User;
import com.test.user.vo.RoleVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author清梦
* @site www.xiaomage.com
* @company xxx公司
* @create 2023-05-06 14:42
*/
@Repository
@Mapper
public interface UserMapper extends BaseMapper<User> {
@Select("select ur.role_id,r.role_code from user_role ur join role r on ur.role_id = r.id where user_id = #{userId} ")
List<RoleVo> selectRole(Integer userId);
@Select("select distinct(permission_code) from permission")
List<String> selectAllPermission();
@Select("select distinct(role_code) from role")
List<String> selectAllRole();
}
service
package com.test.user.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.test.user.entity.User;
import java.util.List;
import java.util.Map;
/**
* @author清梦
* @site www.xiaomage.com
* @company xxx公司
* @create 2023-05-06 14:44
*/
public interface UserService extends IService<User> {
List<User> getUserList();
void delete(Integer userId);
}
实现类
package com.test.user.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.user.entity.CustomerUserDetails;
import com.test.user.entity.RoleMenu;
import com.test.user.entity.User;
import com.test.user.entity.UserRole;
import com.test.user.enums.UserTypeEnum;
import com.test.user.mapper.RoleMenuMapper;
import com.test.user.mapper.UserMapper;
import com.test.user.mapper.UserRoleMapper;
import com.test.user.service.RoleMenuService;
import com.test.user.service.UserService;
import com.test.user.vo.RoleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author清梦
* @site www.xiaomage.com
* @company xxx公司
* @create 2023-05-06 14:45
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserDetailsService, UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private RoleMenuMapper roleMenuMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUsername,username);
User user = userMapper.selectOne(queryWrapper);
if (null == user){
log.error("用户名或密码错误");
throw new UsernameNotFoundException("用户名或密码错误");
}
//查询角色及权限
List<String> authoritiesList = new ArrayList<>();
Integer userId = user.getId();
String userType = user.getUserType();
log.info("userType:{}",userType.toString());
List<RoleVo> roleVos = userMapper.selectRole(userId);
List<String> authPermissions = new ArrayList<>();
List<String> roleList = new ArrayList<>();
List<String> finalRoleList = roleList;
List<String> finalAuthPermissions = authPermissions;
roleVos.stream().forEach(vo->{
finalRoleList.add(vo.getRoleCode());
Integer roleId = vo.getRoleId();
List<String> stringList = roleMenuMapper.selectRoleCodesByRoleID(roleId);
List<String> permissions = new ArrayList<>();
stringList.stream().forEach(list->{
if (StringUtils.isNotBlank(list)){
permissions.addAll(stringToList(list));
}
});
finalAuthPermissions.addAll(permissions);
});
if (UserTypeEnum.ROOT.getCode().equals(userType)){
authPermissions = userMapper.selectAllPermission();
roleList = userMapper.selectAllRole();
authoritiesList.addAll(authPermissions);
authoritiesList.addAll(roleList);
}else {
authoritiesList.addAll(finalAuthPermissions);
authoritiesList.addAll(finalRoleList);
}
log.info("{}的权限:{}",user.getUsername(),authPermissions.toString());
log.info("{}的角色:{}",user.getUsername(),roleList.toString());
authoritiesList = authoritiesList.stream().distinct().collect(Collectors.toList());
CustomerUserDetails customerUserDetails = new CustomerUserDetails(user, authoritiesList);
return customerUserDetails;
}
public List<String> stringToList(String list){
return Arrays.asList(list.split(","));
}
@Override
public List<User> getUserList() {
return userMapper.selectList(null);
}
@Override
@Transactional
public void delete(Integer userId) {
//1.删除该用户关联的角色菜单记录
LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(UserRole::getUserId,userId);
int delete = userRoleMapper.delete(queryWrapper);
log.info("删除了{}条记录",delete);
//2.删除用户
userMapper.deleteById(userId);
}
}
vo
package com.test.user.vo;
import lombok.Data;
/**
* @author清梦
* @site www.xiaomage.com
* @company xxx公司
* @create 2023-05-12 20:03
*/
@Data
public class RoleVo {
private Integer roleId;
private String roleCode;
}
页面
注意:使用thymeleaf语法的页面必须放在/resource/templates/目录下
如图
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>后台管理系统</title>
</head>
<body>
<form action="/logout" method="get">
<input type="submit" value="注销">
</form>
<button><a href="/menu/toList">菜单管理</a></button>
<button><a href="/toUserList">用户管理</a></button>
<button><a href="/role/toList">角色管理</a></button>
<button><a href="/permission/toList">权限管理</a></button>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<h1>欢迎登录XXX系统</h1>
<form action="/login" method="post">
用户名 <input type="text" name="username"><br/>
密码 <input type="password" name="password"><br/>
<button>登录</button>
</form>
</body>
</html>
403.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>403</title>
</head>
<body>
<h1>没有访问权限,请联系管理员</h1>
</body>
</html>
addUser.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>添加用户</title>
</head>
<body>
<form action="/addUser" method="post">
用户名<input type="text" name="username"/><br/>
密码<input type="text" name="password"/><br/>
电话号码<input type="text" name="phone"/><br/>
用户类型
<input type="radio" name="userType" value="1"/>超级管理员
<input type="radio" name="userType" value="0"/>普通用户<br/>
<input type="submit" value="保存"/>
</form>
</body>
</html>
updateUser.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>编辑用户</title>
</head>
<body>
<form action="/updateUser" method="post">
用户id<input type="number" name="id" th:value="${user.id}"/><br/>
用户名<input type="text" name="username" th:value="${user.username}"/><br/>
密码<input type="text" name="password" th:value="${user.password}"/><br/>
电话号码<input type="text" name="phone" th:value="${user.phone}"/><br/>
用户类型<input type="text" name="userType" th:value="${user.userType}"/><br/>
<input type="submit" value="保存"/>
</form>
</body>
</html>
userList.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户管理</title>
</head>
<body>
<a href="/toAddUser">添加用户</a><br/>
<a href="/index.html">返回首页</a>
<table border="1" cellpadding="1" cellspacing="1">
<tr>
<th>用户id</th>
<th>用户名</th>
<th>密码</th>
<th>电话号码</th>
<th>用户类型</th>
<th>创建时间</th>
<th>创建用户</th>
<th>更新时间</th>
<th>更新用户</th>
<th>操作</th>
</tr>
<tr th:each="user,status:${userList}">
<td th:text="${user.id}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.password}"></td>
<td th:text="${user.phone}"></td>
<td th:text="${user.userType == '1'?'超级管理员':'普通用户'}"></td>
<td th:text="${#dates.format(user.createTime,'yyyy-MM-dd HH:mm:ss')}"></td>
<td th:text="${user.createUser}"></td>
<td th:text="${#dates.format(user.updateTime,'yyyy-MM-dd HH:mm:ss')}"></td>
<td th:text="${user.updateUser}"></td>
<td>
<a th:href="'/delete?id='+${user.id}">删除</a>
<a th:href="'/toEditUser?id='+${user.id}">编辑</a>
<a href="/userRole/toList">配置角色</a>
</td>
</tr>
</table>
</body>
</html>
其他模块管理代码看源码,基本雷同。
运行
运行项目
启动成功后,打开浏览器,输入
http://localhost:9011/,即可进入首页,
查看其他菜单需要登录,输入用户名:admin,密码:123456,以超级管理员登入,拥有所有权限;输入用户名:查询角色,密码:123456,只能查看列表。
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。