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 }

 

posted @ 2019-04-10 20:34  SpringCore  阅读(2166)  评论(0编辑  收藏  举报