⒈通用RBAC(Role - Based Access Control)數據模型java
⒉如何使用spring
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.ide
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調用咱們的方法url
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 }