介绍

本系统为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-testdatasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/wechat?serverTimezone=Asia/Shanghai&characterEncoding=utf-8username: rootpassword: 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 {@Overridepublic 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);}}@Overridepublic 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 {@Resourceprivate UserDetailsService userDetailsService;@BeanPasswordEncoder getPasswordEncoder(){return new BCryptPasswordEncoder();}//security的鉴权排除列表private static final String [] excludeAuthPages = {"/user/login","/login"};@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());}@Overrideprotected 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 {@AutowiredUserService userService;@AutowiredPasswordEncoder 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 {@Autowiredprivate UserMapper userMapper;@Autowiredprivate UserRoleMapper userRoleMapper;@Autowiredprivate RoleMenuMapper roleMenuMapper;@Overridepublic 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(","));}@Overridepublic List<User> getUserList() {return userMapper.selectList(null);}@Override@Transactionalpublic 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,只能查看列表。

springboot整合security,mybatisPlus,thymeleaf实现登录认证及用户,菜单,角色权限管理相关推荐

  1. SpringBoot 整合Security——自定义表单登录

    文章目录 一.添加验证码 1.1 验证servlet 1.2 修改 login.html 1.3 添加匿名访问 Url 二.AJAX 验证 三.过滤器验证 3.1 编写验证码过滤器 3.2 注入过滤器 ...

  2. 统一Portal门户和IAM平台(单点登录、统一用户资源和权限管理)实践

    一.背景和目的 解决如下问题: 打通所有系统的账户密码,只需要记住一个就行,而且登录一个系统后,打开其他系统不需要再登录. 不需要记住多个系统的地址,甚至不需要在多个系统页面跳来跳去,通过一个门户网站 ...

  3. springboot整合swagger+mybatisplus案例

    1.前后端分离的一个常用的文档接口swaggerui越来越受欢迎,方便了前端以及后端人员的测试 2.如下为springboot整合swagger和mybatispus案例的github地址:https ...

  4. 一篇搞定 SpringBoot+Mybatis+Shiro 实现多角色权限管理

    初衷:我在网上想找整合springboot+mybatis+shiro并且多角色认证的博客,发现找了好久也没有找到想到的,现在自己会了,就打算写个博客分享出去,希望能帮到你. 原创不易,请点赞支持! ...

  5. springboot整合shiro+mybatis-plus

    文章目录 Shiro框架简介 环境搭建springboot+shiro+mybatis-plus+thymeleaf 1.创建Spring Boot项目,集成Shiro及相关组件 2.准备一个sql表 ...

  6. Springboot 整合微信小程序实现登录与增删改查

    点击上方 好好学java ,选择 星标 公众号 重磅资讯.干货,第一时间送达 今日推荐:我的大学到研究生自学 Java 之路,过程艰辛,不放弃,保持热情,最终发现我是这样拿到大厂 offer 的! 作 ...

  7. springboot+mybatis+Oauth2 +vue 框架实现登录认证

    1.最近在研究前后端分离项目,领导安排任务:使用Oauth2实现登录认证.因为第一次接触vue对里面的结构方法使用情况等不是很了解走了很多弯路.现在记录使用Oauth2实现登录认证,供大家参考. 2. ...

  8. springboot 整合 swagger2 配置账号密码登录 demo代码

    配置spring security登录可参考: springboot整合spring security安全框架-简单验证账号密码 一.pom文件引入swagger依赖 <!-- swagger2 ...

  9. springboot整合视图层Thymeleaf、freemarker

    springboot整合视图层以thymeleaf和freemarker为例 1.整合Thymeleaf 主要配置application.properties #是否开启缓存,默认为true spri ...

最新文章

  1. 人工智能热潮下,我们该如何紧跟科技脚步呢?
  2. 小技巧—设置IIS禁止网站放下载电影文件
  3. Apache Payara:让我们加密
  4. java web 项目如何获取客户端登录帐号信息(用于SSO或其他)
  5. Java电话号码滚动抽奖_js手机号码批量滚动抽奖代码实现
  6. 设计模式 (二十一) 策略模式
  7. 上平台! 车联网智能化晋级高段位!
  8. Ant design vue 表格合并 合并行 合并列
  9. python语音引擎深度学习_基于Python的深度学习BP网络语音增强方法研究
  10. 如何用计算机输入数学符号,x的平方怎么在电脑上打出来(常见数学符号打法...
  11. 5G系统——连接管理CM
  12. 浏览器端反爬虫特征收集之字体检测
  13. office邮箱不能预览附件问题
  14. 哪个平台回收速度快?
  15. 高级刀片服务器系统,刀片服务器系统
  16. 这5个“计算机专业”就业很吃香,毕业生需求量大,还不会过时
  17. LLVM WEEKLY系列停止转载
  18. 给你一本武林秘籍,和KeeWiDB一起登顶高性能
  19. 在线文库系统 文档在线预览 文库分享网站
  20. ​Mac下 VSCode快捷键 VSCode基本使用

热门文章

  1. mysql 一致性hash_韩信大招:一致性哈希
  2. 索引的优缺点以及如何创建索引
  3. 几种方法,彻底删除电脑弹窗广告,还你一个干净的桌面~
  4. P5.js开发之——通过createImg向页面中添加图像
  5. pythonic风格_什么样的函数才叫 Pythonic
  6. 达芬奇系列DSP——CCS_V5安装技术文档
  7. Android WebView跳转浏览器下载或打开第三方应用
  8. 如何使用Java官网
  9. 天津市滨海产业基金管理有限公司招聘公告
  10. 数字芯片设计中常见的三个握手协议