乐趣区

关于java:别再用过时的方式了全新版本Spring-Security这样用才够优雅

前不久 Spring Boot 2.7.0 刚刚公布,Spring Security 也降级到了 5.7.1。降级后发现,原来始终在用的 Spring Security 配置办法,竟然曾经被弃用了。不禁感叹技术更新真快,用着用着就被弃用了!明天带大家体验下 Spring Security 的最新用法,看看是不是够优雅!

SpringBoot 实战电商我的项目 mall(50k+star)地址:https://github.com/macrozheng/mall

根本应用

咱们先比照下 Spring Security 提供的基本功能登录认证,来看看新版用法是不是更好。

降级版本

首先批改我的项目的 pom.xml 文件,把 Spring Boot 版本升级至 2.7.0 版本。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.0</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

旧用法

在 Spring Boot 2.7.0 之前的版本中,咱们须要写个配置类继承WebSecurityConfigurerAdapter,而后重写 Adapter 中的三个办法进行配置;

/**
 * SpringSecurity 的配置
 * Created by macro on 2018/4/26.
 */
@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,只需间接申明配置类,再配置一个生成SecurityFilterChainBean 的办法,把原来的 HttpSecurity 配置挪动到该办法中即可。

/**
 * SpringSecurity 5.4.x 以上新用法配置
 * 为防止循环依赖,仅用于配置 HttpSecurity
 * Created by macro on 2022/5/19.
 */
@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 的配置
 * Created by macro on 2018/4/26.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OldSecurityConfig extends WebSecurityConfigurerAdapter {}
  • 而后在办法中应用 @PreAuthorize 配置拜访接口须要的权限;
/**
 * 商品治理 Controller
 * Created by macro on 2018/4/26.
 */
@Controller
@Api(tags = "PmsProductController", description = "商品治理")
@RequestMapping("/product")
public class PmsProductController {
    @Autowired
    private PmsProductService productService;

    @ApiOperation("创立商品")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    @PreAuthorize("hasAuthority('pms:product:create')")
    public CommonResult create(@RequestBody PmsProductParam productParam, BindingResult bindingResult) {int count = productService.create(productParam);
        if (count > 0) {return CommonResult.success(count);
        } else {return CommonResult.failed();
        }
    }
}
  • 再从数据库中查问出用户所领有的权限值设置到 UserDetails 对象中去,这种做法尽管实现不便,然而把权限值写死在了办法上,并不是一种优雅的做法。
/**
 * UmsAdminService 实现类
 * Created by macro on 2018/4/26.
 */
@Service
public class UmsAdminServiceImpl implements UmsAdminService {
    @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 办法来进行鉴权操作;
/**
 * 动静权限过滤器,用于实现基于门路的动静权限过滤
 * Created by macro on 2020/2/7.
 */
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 办法对拜访接口所需权限和用户领有的权限进行匹配,匹配则放行;
/**
 * 动静权限决策管理器,用于判断用户是否有拜访权限
 * Created by macro on 2020/2/7.
 */
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 属性是从 FilterInvocationSecurityMetadataSourcegetAttributes办法中获取的,咱们还需创立一个类继承它,getAttributes办法可用于获取拜访以后门路所需权限值;
/**
 * 动静权限数据源,用于获取动静权限规定
 * Created by macro on 2020/2/7.
 */
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
/**
 * 动静权限相干业务类
 * Created by macro on 2020/2/7.
 */
public interface DynamicSecurityService {
    /**
     * 加载资源 ANT 通配符和资源对应 MAP
     */
    Map<String, ConfigAttribute> loadDataSource();}
  • 所有准备就绪,把动静权限过滤器增加到 FilterSecurityInterceptor 之前;
/**
 * SpringSecurity 5.4.x 以上新用法配置
 * 为防止循环依赖,仅用于配置 HttpSecurity
 * Created by macro on 2022/5/19.
 */
@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 模块相干配置
 * 自定义配置,用于配置如何获取用户信息及动静权限
 * Created by macro on 2022/5/20.
 */
@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;
            }
        };
    }

}

成果测试

  • 接下来启动咱们的示例我的项目 mall-tiny-security,应用如下账号密码登录,该账号只配置了拜访/brand/listAll 的权限,拜访地址:http://localhost:8088/swagger…

  • 而后把返回的 token 放入到 Swagger 的认证头中;

  • 当咱们拜访有权限的接口时能够失常获取到数据;

  • 当咱们拜访没有权限的接口时,返回没有拜访权限的接口提醒。

总结

Spring Security 的降级用法的确够优雅,够简略,而且对之前用法的兼容性也比拟好!个人感觉一个成熟的框架不太会在降级过程中大改用法,即便改了也会对之前的用法做兼容,所以对于绝大多数框架来说旧版本会用,新版本照样会用!

参考资料

本文仅仅是对 Spring Security 新用法的总结,如果你想理解 Spring Security 更多用法,能够参考下之前的文章。

  • mall 整合 SpringSecurity 和 JWT 实现认证和受权(一)
  • mall 整合 SpringSecurity 和 JWT 实现认证和受权(二)
  • 仅需四步,整合 SpringSecurity+JWT 实现登录认证!
  • 手把手教你搞定权限治理,联合 Spring Security 实现接口的动静权限管制!

我的项目源码地址

https://github.com/macrozheng…

退出移动版