前不久Spring Boot 2.7.0 刚刚发布,Spring Security 也升级到了5.7.1 。升级后发现,原来一直在用的Spring Security配置方法,居然已经被弃用了。不禁感慨技术更新真快,用着用着就被弃用了!今天带大家体验下Spring Security的最新用法,看看是不是够优雅!
基本使用
在Spring Boot 2.7.0 之前的版本中,我们需要写个配置类继承WebSecurityConfigurerAdapter ,然后重写Adapter中的三个方法进行配置;
/** * SpringSecurity的配置 */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class OldSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UmsAdminService adminService; @Override protected void configure(HttpSecurity httpSecurity) throws Exception { //省略HttpSecurity的配置 } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()) .passwordEncoder(passwordEncoder()); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
如果你在SpringBoot 2.7.0版本中进行使用的话,你就会发现WebSecurityConfigurerAdapter 已经被弃用了,看样子Spring Security要坚决放弃这种用法了!
新用法非常简单,无需再继承WebSecurityConfigurerAdapter ,只需直接声明配置类,再配置一个生成 SecurityFilterChain Bean的方法,把原来的HttpSecurity配置移动到该方法中即可。
/** * SpringSecurity 5.4.x以上新用法配置 * 为避免循环依赖,仅用于配置HttpSecurity */ @Configuration public class SecurityConfig { @Bean SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { //省略HttpSecurity的配置 return httpSecurity.build(); } }
新用法感觉非常简洁干脆,避免了继承WebSecurityConfigurerAdapter 并重写方法的操作,强烈建议大家更新一波!
高级使用
Spring Boot 2.7.0版本后,Spring Security对于配置方法有了大的更改,那么其他使用有没有影响呢?其实是没啥影响的,这里再聊聊如何使用Spring Security实现动态权限控制!
基于方法的动态权限
基于方法的动态权限控制,这种方式虽然实现简单,但却有一定的弊端。
- 在配置类上使用 @EnableGlobalMethodSecurity 来开启它;
/** * SpringSecurity的配置 */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class OldSecurityConfig extends WebSecurityConfigurerAdapter { }
- 然后在方法中使用 @PreAuthorize 配置访问接口需要的权限;
/** * Controller */ @Controller @RequestMapping("/test") public class TestController { @RequestMapping(value = "/test", method = RequestMethod.GET) @ResponseBody @PreAuthorize("hasAuthority('some:function:create')") public R test() { return R.success(count); } }
- 再从数据库中查询出用户所拥有的权限值设置到 UserDetails 对象中去,这种做法虽然实现方便,但是把权限值写死在了方法上,并不是一种优雅的做法。
/** * UserService实现类 */ @Service public class UserServiceImpl implements IUserService { @Override public UserDetails loadUserByUsername(String username){ //获取用户信息 UmsAdmin admin = getAdminByUsername(username); if (admin != null) { List<UmsPermission> permissionList = getPermissionList(admin.getId()); return new AdminUserDetails(admin, permissionList); } throw new UsernameNotFoundException("用户名或密码错误"); } }
- 基于路径的动态权限
其实每个接口对应的路径都是唯一的,通过路径来进行接口的权限控制才是更优雅的方式。
- doFilter OPTIONS 白名单 super.beforeInvocation(fi) AccessDecisionManager decide
/** * 动态权限过滤器,用于实现基于路径的动态权限过滤 */ public class DynamicSecurityFilter extends AbstractSecurityInterceptor implements Filter { @Autowired private DynamicSecurityMetadataSource dynamicSecurityMetadataSource; @Autowired private IgnoreUrlsConfig ignoreUrlsConfig; @Autowired public void setMyAccessDecisionManager(DynamicAccessDecisionManager dynamicAccessDecisionManager) { super.setAccessDecisionManager(dynamicAccessDecisionManager); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain); //OPTIONS请求直接放行 if(request.getMethod().equals(HttpMethod.OPTIONS.toString())){ fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); return; } //白名单请求直接放行 PathMatcher pathMatcher = new AntPathMatcher(); for (String path : ignoreUrlsConfig.getUrls()) { if(pathMatcher.match(path,request.getRequestURI())){ fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); return; } } //此处会调用AccessDecisionManager中的decide方法进行鉴权操作 InterceptorStatusToken token = super.beforeInvocation(fi); try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.afterInvocation(token, null); } } @Override public void destroy() { } @Override public Class<?> getSecureObjectClass() { return FilterInvocation.class; } @Override public SecurityMetadataSource obtainSecurityMetadataSource() { return dynamicSecurityMetadataSource; } }
- 接下来我们就需要创建一个类来继承 AccessDecisionManager ,通过 decide 方法对访问接口所需权限和用户拥有的权限进行匹配,匹配则放行;
/** * 动态权限决策管理器,用于判断用户是否有访问权限 */ public class DynamicAccessDecisionManager implements AccessDecisionManager { @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { // 当接口未被配置资源时直接放行 if (CollUtil.isEmpty(configAttributes)) { return; } Iterator<ConfigAttribute> iterator = configAttributes.iterator(); while (iterator.hasNext()) { ConfigAttribute configAttribute = iterator.next(); //将访问所需资源或用户拥有资源进行比对 String needAuthority = configAttribute.getAttribute(); for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) { if (needAuthority.trim().equals(grantedAuthority.getAuthority())) { return; } } } throw new AccessDeniedException("抱歉,您没有访问权限"); } @Override public boolean supports(ConfigAttribute configAttribute) { return true; } @Override public boolean supports(Class<?> aClass) { return true; } }
- decide configAttributes FilterInvocationSecurityMetadataSource getAttributes getAttributes
/** * 动态权限数据源,用于获取动态权限规则 */ public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { private static Map<String, ConfigAttribute> configAttributeMap = null; @Autowired private DynamicSecurityService dynamicSecurityService; @PostConstruct public void loadDataSource() { configAttributeMap = dynamicSecurityService.loadDataSource(); } public void clearDataSource() { configAttributeMap.clear(); configAttributeMap = null; } @Override public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException { if (configAttributeMap == null) this.loadDataSource(); List<ConfigAttribute> configAttributes = new ArrayList<>(); //获取当前访问的路径 String url = ((FilterInvocation) o).getRequestUrl(); String path = URLUtil.getPath(url); PathMatcher pathMatcher = new AntPathMatcher(); Iterator<String> iterator = configAttributeMap.keySet().iterator(); //获取访问该路径所需资源 while (iterator.hasNext()) { String pattern = iterator.next(); if (pathMatcher.match(pattern, path)) { configAttributes.add(configAttributeMap.get(pattern)); } } // 未设置操作请求权限,返回空集合 return configAttributes; } @Override public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } @Override public boolean supports(Class<?> aClass) { return true; } }
- 这里需要注意的是,所有路径对应的权限值数据来自于自定义的 DynamicSecurityService ;
/** * 动态权限相关业务类 */ public interface DynamicSecurityService { /** * 加载资源ANT通配符和资源对应MAP */ Map<String, ConfigAttribute> loadDataSource(); }
- 一切准备就绪,把动态权限过滤器添加到 FilterSecurityInterceptor 之前;
/** * SpringSecurity 5.4.x以上新用法配置 * 为避免循环依赖,仅用于配置HttpSecurity */ @Configuration public class SecurityConfig { @Autowired private DynamicSecurityService dynamicSecurityService; @Autowired private DynamicSecurityFilter dynamicSecurityFilter; @Bean SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { //省略若干配置... //有动态权限配置时添加动态权限校验过滤器 if(dynamicSecurityService!=null){ registry.and().addFilterBefore(dynamicSecurityFilter, FilterSecurityInterceptor.class); } return httpSecurity.build(); } }
- 如果你看过这篇 仅需四步,整合SpringSecurity+JWT实现登录认证 ! 的话,就知道应该要配置这两个Bean了,一个负责获取登录用户信息,另一个负责获取存储的动态权限规则,为了适应Spring Security的新用法,我们不再继承 SecurityConfig ,简洁了不少!
/** * mall-security模块相关配置 * 自定义配置,用于配置如何获取用户信息及动态权限 */ @Configuration public class MallSecurityConfig { @Autowired private UmsAdminService adminService; @Bean public UserDetailsService userDetailsService() { //获取登录用户信息 return username -> { AdminUserDetails admin = adminService.getAdminByUsername(username); if (admin != null) { return admin; } throw new UsernameNotFoundException("用户名或密码错误"); }; } @Bean public DynamicSecurityService dynamicSecurityService() { return new DynamicSecurityService() { @Override public Map<String, ConfigAttribute> loadDataSource() { Map<String, ConfigAttribute> map = new ConcurrentHashMap<>(); List<UmsResource> resourceList = adminService.getResourceList(); for (UmsResource resource : resourceList) { map.put(resource.getUrl(), new org.springframework.security.access.SecurityConfig(resource.getId() + ":" + resource.getName())); } return map; } }; } }
文章评论