1. 程式人生 > 程式設計 >SpringSecurity 吐槽篇

SpringSecurity 吐槽篇

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 官方預設實現,在很長的一段時間內,依然會是主流,如果不能反抗,那就享受吧.