Spring Security 不允许资源

Kir*_*rov 1 spring-security spring-boot

我有配置

http.csrf().disable();
    http.authorizeRequests()
                    .antMatchers("/**").authenticated()
                    .antMatchers("/shutdown").permitAll()
                    .and().formLogin().passwordParameter("password").usernameParameter("username")
                    .and().formLogin().loginPage("/authentication.html").permitAll()
                    .and().formLogin().loginProcessingUrl("/login")
                    .and().formLogin().failureUrl("/authentication.html")
                    .and().formLogin().defaultSuccessUrl("/",false);
Run Code Online (Sandbox Code Playgroud)

身份验证工作完美,但我无法在没有身份验证的情况下访问 /shutdown。这可能是什么原因?

/shutdown - 弹簧启动的关闭钩子。

Rob*_*nch 5

如前所述,“/**”表示任何请求,并且只会使用匹配的第一个模式。需要注意的一件事是,您可以大量清理配置。请参阅下面的清洁版本:

http
   .csrf().disable()
   .authorizeRequests()
       .antMatchers("/shutdown").permitAll()
       .anyRequest().authenticated()
       .and()
   .formLogin()
       .loginPage("/authentication.html")
       .loginProcessingUrl("/login")
       .failureUrl("/authentication.html")
       .permitAll();
Run Code Online (Sandbox Code Playgroud)

变化亮点:

  • 您不应该需要键入 http 两次。您当然可以这样做,但这不是必需的,它可以节省您的输入
  • .antMatchers("/**") 有一个 .anyRequest() 的别名,它读起来好多了
  • 为 .formLogin() 指定属性时,您只需指定 .formLogin() 一次。比如,http,你可以多次声明,但不这样做会简洁得多
  • defaultSuccessUrl 不需要 false 参数(它相当于一起省略参数)。例如,您可以声明 .defaultSuccessUrl("/"),而不是 .defaultSuccessUrl("/", false)。此外,.defaultSuccessUrl 的默认值已经是“/”。这意味着您可以将其全部删除。
  • 您会注意到我遵循了本博客中概述的 JavaConfig 的确切格式