SpringSecurity基于数据库RBAC数据模型控制权限

⒈通用RBAC(Role - Based Access Control)数据模型

SpringSecurity基于数据库RBAC数据模型控制权限

⒉如何使用

  1.

  

 package cn.coreqi.ssoserver.rbac;

 import org.springframework.security.core.Authentication;

 import javax.servlet.http.HttpServletRequest;

 public interface RbacService {

     /**
*
* @param request 当前请求的信息
* @param authentication 当前用户的信息
* @return 是否拥有访问权限
*/
boolean hasPermission(HttpServletRequest request, Authentication authentication);
}

  2.

 package cn.coreqi.ssoserver.rbac.impl;

 import cn.coreqi.ssoserver.rbac.RbacService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher; import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set; @Component("rbacService")
public class RbacServiceImpl implements RbacService { private AntPathMatcher antPathMatcher = new AntPathMatcher(); /**
*
* @param request 当前请求的信息
* @param authentication 当前用户的信息
* @return 是否拥有访问权限
*/
@Override
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
Object principal = authentication.getPrincipal();
boolean hasPermission = false;
if(principal instanceof UserDetails){
String username = ((UserDetails)principal).getUsername();
//在数据库中读取用户所拥有权限的所有URL
//在这里使用Set模拟
Set<String> urls = new HashSet<>();
for (String url : urls){
if(antPathMatcher.match(url,request.getRequestURI())){
hasPermission = true;
break;
}
}
}
return hasPermission;
}
}

  3.写一个权限表达式,让SpringSecurity调用我们的方法

 @EnableWebSecurity
public class SsoWebSecurityConfig extends WebSecurityConfigurerAdapter { @Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.and()
.authorizeRequests()
.anyRequest().access("@rbacService.hasPermission(request, authentication)") //为了避免该配置被覆盖,必要时需要使用@Order注解设置优先级。
.and()
.csrf().disable(); //禁用CSRF
} }
上一篇:java——获取从控制台输入的数据的方法


下一篇:SpringBoot 分页处理