SpringSecurity基于数据库RBAC数据模型控制权限
⒈通用RBAC(Role - Based Access Control)数据模型
⒉如何使用
1.
1 package cn.coreqi.ssoserver.rbac; 2 3 import org.springframework.security.core.Authentication; 4 5 import javax.servlet.http.HttpServletRequest; 6 7 public interface RbacService { 8 9 /** 10 * 11 * @param request 当前请求的信息 12 * @param authentication 当前用户的信息 13 * @return 是否拥有访问权限 14 */ 15 boolean hasPermission(HttpServletRequest request, Authentication authentication); 16 }
2.
1 package cn.coreqi.ssoserver.rbac.impl; 2 3 import cn.coreqi.ssoserver.rbac.RbacService; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.security.core.Authentication; 6 import org.springframework.security.core.userdetails.UserDetails; 7 import org.springframework.stereotype.Component; 8 import org.springframework.util.AntPathMatcher; 9 10 import javax.servlet.http.HttpServletRequest; 11 import java.util.HashSet; 12 import java.util.Set; 13 14 @Component("rbacService") 15 public class RbacServiceImpl implements RbacService { 16 17 private AntPathMatcher antPathMatcher = new AntPathMatcher(); 18 19 /** 20 * 21 * @param request 当前请求的信息 22 * @param authentication 当前用户的信息 23 * @return 是否拥有访问权限 24 */ 25 @Override 26 public boolean hasPermission(HttpServletRequest request, Authentication authentication) { 27 Object principal = authentication.getPrincipal(); 28 boolean hasPermission = false; 29 if(principal instanceof UserDetails){ 30 String username = ((UserDetails)principal).getUsername(); 31 //在数据库中读取用户所拥有权限的所有URL 32 //在这里使用Set模拟 33 Set<String> urls = new HashSet<>(); 34 for (String url : urls){ 35 if(antPathMatcher.match(url,request.getRequestURI())){ 36 hasPermission = true; 37 break; 38 } 39 } 40 } 41 return hasPermission; 42 } 43 }
3.写一个权限表达式,让SpringSecurity调用我们的方法
1 @EnableWebSecurity 2 public class SsoWebSecurityConfig extends WebSecurityConfigurerAdapter { 3 4 @Override 5 protected void configure(HttpSecurity http) throws Exception { 6 http.formLogin() 7 .and() 8 .authorizeRequests() 9 .anyRequest().access("@rbacService.hasPermission(request, authentication)") //为了避免该配置被覆盖,必要时需要使用@Order注解设置优先级。 10 .and() 11 .csrf().disable(); //禁用CSRF 12 } 13 14 }
作者:奇
出处:https://www.cnblogs.com/fanqisoft/p/10685937.html
版权:本作品采用「本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。」许可协议进行许可。
如果文章内容对您有所帮助,欢迎赞赏.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!