Keep it simple, stupid
配置复杂难以理解
以一段配置为例
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/i18n/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(http401UnauthorizedEntryPoint())
.and()
.csrf()
.disable()
.headers()
.disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.antMatchers("/actuator/**").access(actuatorExp)
.antMatchers("/user/register/").hasAuthority(AuthoritiesConstants.API_REGISTER.getValue())
.antMatchers("/**").hasAuthority(AuthoritiesConstants.USER.getValue())
.antMatchers("/pick/**").hasAuthority(AuthoritiesConstants.PICKER.getValue())
.and()
.securityContext()
.securityContextRepository(new NullSecurityContextRepository())
.and()
.apply(securityConfigurerAdapter());
if (verificationSecurityConfigurer != null) {
http.apply(verificationSecurityConfigurer);
}
}
WebSecurity 与 HttpSecurity 什么关系, 能不能统一到一起配置?
HttpSeecurity 的配置从上到下没有层次感, 需要了解足够多的内部配置信息才能准确配置.
"Explicit is better than implicit", Spring Security 默认启用的配置10+, 都是隐式配置, 但是需要显式的 disable .
优化用户体验?
下面也许更好
http
.apply(sessionConfigurer)
.apply(csryConfigurer)
.apply(contextConfigurer)
.apply(authorizeConfigurer)
.apply(customConfigurer)
- 显式配置, 提供默认配置的实现, 但不默认配置.
- 具体配置由配置类实现, 不在顶层配置.
实现复杂
实现获取 Token, 验证, 授权, 访问控制使用的都是 Filter. 而且 Filter 还是 Servlet 规范的 Filter , 对使用者而言, 不免混淆.
Filter 过于强大(强大到可以基于 FIlter 实现 Struts2 框架 ), 而 Spring Security 并未对此设限.
以异常处理来做业务逻辑. 这个也是不得已为之, 毕竟基于 Filter
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException;
Filter 的核心方法 doFilter 是没有返回值的 以异常处理做业务处理的问题, 就是重拾万恶的GOTO 语句
END
当然, Spring Security 被广泛使用的原因在于它确实可以满足用户的安全需求, 尽管并不好用. 有没有更简单的安全框架, 也许 Shiro 是个不错的选择, 但个人并没有进一步了解, 此处不表.
由于 Spring Security 是 Spring 官方默认实现, 在很长的一段时间内, 依然会是主流, 如果不能反抗, 那就享受吧.