提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
springboot+mybatisplus整合springsecurity
默认springboot+mybatisplus已经整合好
数据库表,我们使用标准权限系统表5张,分别为:
sys_user 用户表
sys_role 角色表
sys_menu 权限菜单表
sys_user_role 用户角色关联表
sys_role_menu 角色权限关联表
提示:以下是本篇文章正文内容,下面案例可供参考
一、引jar和 application.yml配置:
| |
| <dependency> |
| <groupId>org.springframework.boot</groupId> |
| <artifactId>spring-boot-starter-security</artifactId> |
| </dependency> |
| |
| spring: |
| datasource: |
| druid: |
| url: jdbc:mysql://localhost:3306/db_permission_system_security?useUnicode=true&characterEncoding=utf-8 |
| username: root |
| password: root |
| initial-size: 5 |
| max-active: 20 |
| min-idle: 10 |
| max-wait: 10 |
| |
| time-between-eviction-runs-millis: 60000 |
| web: |
| resources: |
| |
| static-locations: classpath:/static/,classpath:/templates/, |
| |
| mybatis-plus: |
| configuration: |
| log-impl: org.apache.ibatis.logging.stdout.StdOutImpl |
| |
| mapper-locations: mapper/*.xml |
| |
| server: |
| port: 18888 |
二、 编写和用户角色权限相关的查询
| package com.aaa.sbmp.mapper; |
| |
| import com.aaa.sbmp.entity.Menu; |
| import com.aaa.sbmp.entity.Role; |
| import com.aaa.sbmp.entity.User; |
| import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
| |
| import java.util.List; |
| |
| |
| |
| |
| |
| |
| |
| |
| public interface UserMapper extends BaseMapper<User> { |
| |
| |
| |
| |
| |
| |
| List<Role> queryRoleListByUserName(String userName); |
| |
| |
| |
| |
| |
| |
| List<Menu> queryMenuListByUserName(String userName); |
| } |
| |
| <?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.aaa.sbmp.mapper.UserMapper"> |
| |
| |
| <select id="queryRoleListByUserName" resultType="com.aaa.sbmp.entity.Role"> |
| select role_Id roleId,role_Name roleName,role_Key roleKey from sys_role r where exists( |
| select 1 from sys_user_role ur where ur.user_id=( |
| select user_id from sys_user u where u.user_name=#{userName} and status=0 and del_flag=0 |
| ) and ur.role_id=r.role_id |
| ) and status=0 and del_flag=0 |
| </select> |
| |
| <select id="queryMenuListByUserName" resultType="com.aaa.sbmp.entity.Menu"> |
| select menu_Id menuId,menu_Name menuName,perms from sys_menu m where m.visible=0 and exists( |
| select menu_id from sys_role_menu rm where exists ( |
| select role_id from sys_user_role ur where ur.user_id= |
| ( select user_id from sys_user u where u.user_name=#{userName} and status=0 and del_flag=0) |
| and rm.role_id=ur.role_id |
| ) and m.menu_id=rm.menu_id |
| ) |
| </select> |
| </mapper> |
| |
封装到工具控制层
| |
| |
| |
| |
| protected User currentLoadUser(){ |
| Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); |
| return (User)authentication.getPrincipal(); |
| } |
三、编写Security配置
| package com.aaa.sbmp.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.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 javax.annotation.Resource; |
| |
| |
| |
| |
| |
| |
| |
| |
| @Configuration |
| public class SecurityConfig extends WebSecurityConfigurerAdapter { |
| |
| @Resource |
| private UserDetailsService userDetailsService; |
| |
| @Override |
| protected void configure(AuthenticationManagerBuilder auth) throws Exception { |
| auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); |
| } |
| |
| @Bean |
| public BCryptPasswordEncoder passwordEncoder(){ |
| return new BCryptPasswordEncoder(); |
| } |
| |
| @Override |
| protected void configure(HttpSecurity http) throws Exception { |
| |
| http.formLogin() |
| .loginPage("/html/login.html") |
| .loginProcessingUrl("/user/login")登录页面中form配置的请求地址 |
| .failureUrl("/html/login.html?error") |
| .defaultSuccessUrl("/html/index.html").permitAll() |
| .and().authorizeRequests() |
| .antMatchers("/user/login","/","/css/**","/js/**").permitAll() |
| .anyRequest().authenticated() |
| .and().csrf().disable(); |
| |
| http.exceptionHandling().accessDeniedPage("/html/unauthorized.html"); |
| |
| http.logout().logoutUrl("/logout") |
| .logoutSuccessUrl("/html/login.html").permitAll(); |
| |
| } |
| } |
| |
四、服务层
| package com.aaa.sbmp.service.impl; |
| |
| import cn.hutool.core.collection.CollUtil; |
| import cn.hutool.core.util.StrUtil; |
| import com.aaa.sbmp.entity.Menu; |
| import com.aaa.sbmp.entity.Role; |
| import com.aaa.sbmp.entity.User; |
| import com.aaa.sbmp.service.IUserService; |
| import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; |
| import lombok.extern.log4j.Log4j2; |
| import org.springframework.security.core.GrantedAuthority; |
| import org.springframework.security.core.authority.SimpleGrantedAuthority; |
| import org.springframework.security.core.userdetails.UserDetails; |
| import org.springframework.security.core.userdetails.UserDetailsService; |
| import org.springframework.security.core.userdetails.UsernameNotFoundException; |
| import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; |
| import org.springframework.stereotype.Service; |
| |
| import javax.annotation.Resource; |
| import java.util.ArrayList; |
| import java.util.List; |
| |
| |
| |
| |
| |
| |
| |
| |
| @Service |
| @Log4j2 |
| public class UserDetailsServiceImpl implements UserDetailsService { |
| |
| @Resource |
| private IUserService iUserService; |
| |
| @Override |
| public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { |
| |
| List<GrantedAuthority> grantedAuthorityList =new ArrayList<>(); |
| |
| |
| List<Role> roleList = iUserService.queryRoleListByUserName(userName); |
| for (Role role : roleList) { |
| log.info("角色:"+role.getRoleKey()); |
| grantedAuthorityList.add(new SimpleGrantedAuthority(role.getRoleKey())); |
| } |
| |
| List<Menu> menuList = iUserService.queryMenuListByUserName(userName); |
| for (Menu menu : menuList) { |
| String perms = menu.getPerms(); |
| if(StrUtil.isNotEmpty(perms)) { |
| log.info("权限:" + perms); |
| grantedAuthorityList.add(new SimpleGrantedAuthority(perms)); |
| } |
| } |
| |
| QueryWrapper<User> queryWrapper =new QueryWrapper<>(); |
| queryWrapper.eq("user_name",userName); |
| List<User> userList = iUserService.list(queryWrapper); |
| User user = null; |
| |
| if(CollUtil.isNotEmpty(userList)){ |
| user = userList.get(0); |
| } |
| return new org.springframework.security.core.userdetails.User(user.getUserName(), |
| |
| user.getPassword(), |
| grantedAuthorityList); |
| } |
| } |
| |
| package com.aaa.sbmp.service; |
| |
| import com.aaa.sbmp.entity.Menu; |
| import com.aaa.sbmp.entity.Role; |
| import com.aaa.sbmp.entity.User; |
| import com.baomidou.mybatisplus.extension.service.IService; |
| |
| import java.util.List; |
| |
| |
| |
| |
| |
| |
| |
| |
| public interface IUserService extends IService<User> { |
| |
| |
| |
| |
| |
| List<Role> queryRoleListByUserName(String userName); |
| |
| |
| |
| |
| |
| |
| List<Menu> queryMenuListByUserName(String userName); |
| } |
| |
五、前台页面
index。html
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <title>成功首页</title> |
| </head> |
| <body> |
| 成功后的首页 <a href="/logout">用户注销</a> |
| </body> |
| </html> |
login。html
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <title>员工登录</title> |
| <script> |
| function load(){ |
| var url = location.href; |
| |
| if(url.indexOf("?")!=-1){ |
| |
| |
| |
| |
| document.getElementById("errorInfo").innerHTML="用户名或者密码错误!!"; |
| } |
| |
| } |
| |
| </script> |
| </head> |
| <body onload="load()"> |
| <center> |
| <h3>登录页面</h3> |
| <form action="/user/login" method="post"> |
| <div id="errorInfo" style="color: red"></div> |
| <table border="1" > |
| |
| <tr><td>用户名</td><td><input type="text" name="username" value="admin"> </td></tr> |
| <tr><td>密码</td><td><input type="text" name="password" value="tiger"> </td></tr> |
| <tr><td colspan="2" align="center"><input type="submit" value="登录"></td></tr> |
| </table> |
| </form> |
| </center> |
| </body> |
| </html> |
unauthorized.html
| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <title>错误页面</title> |
| </head> |
| <body> |
| 访问了未授权的地址。。。。。。。。。。。 |
| </body> |
| </html> |
六、在启动类添加配置及方法权限注释配置
| @EnableGlobalMethodSecurity(prePostEnabled = true) |
控制层测试方法
| |
| |
| |
| |
| |
| @PreAuthorize("hasRole('管理员')") |
| @GetMapping("queryList") |
| public List<Dept> queryList(Dept dept){ |
| return iDeptService.queryList(dept); |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?