【问题标题】:how to configure spring security for spring boot project如何为spring boot项目配置spring security
【发布时间】:2022-06-12 02:44:11
【问题描述】:

我正在尝试制作一个使用以下内容的 Web 应用程序: 春季启动, mysql, JDBC , MVC, DAO 百里香叶, IntelliJ

我正试图弄清楚 Spring 安全性是如何工作的(我遇到了很多困难)。 我的观点整理如下:

resources(folder): - ________static(folder)
                         |____templates(folder):__________images(folder)
                                                      |___userOnly(folder):_____header.html
                                                      |                       |__help.html
                                                      |                       |__menu.html
                                                      |                       |__newDocForm.html
                                                      |                       |__profil.html
                                                      |
                                                      |__firstPage.html
                                                      |__header.html
                                                      |__home.html
                                                      |__index.html
                                                      |__inscriptionForm.html
                                                      |__loginPage.html

我希望身份不明的用户可以访问除“userOnly”中包含的视图之外的所有视图,并且我的“loginPage”页面用作登录页面。

如果我理解正确,我必须创建一个继承自“WebSecurityConfigurerAdapter”的类。 我做了什么。 然后配置“配置”,我不能正确地做:(

@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/userOnly/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/loginPage.html");
    }
}

对不起,如果我的问题看起来很奇怪,但英语不是我的第一语言

【问题讨论】:

    标签: java spring spring-boot spring-security


    【解决方案1】:

    从 Spring-Boot 2.7 开始,不推荐使用 WebSecurityConfigurerAdapter。如果您使用的是 Spring-Boot 2.6 或更早版本,其他答案可能更适合您。

    据我所知,在 Spring-Boot 2.7 中定义安全配置的推荐方法如下:

    @Configuration
    public class WebSecurityConfig
    {
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception
        {
            // @formatter:off
            http.authorizeRequests()
                .mvcMatchers("/userOnly/**").permitAll()
                .anyRequest().permitAll();
            http.formLogin()
                .permitAll()
                .loginPage("/loginPage.html");
            http.logout()
                .permitAll();
            // @formatter:on
            
            return http.build();
        }
    }
    

    我相信,不推荐在voucher_wolves 的答案中使用 web.ignoring(),而是应该将这些情况添加到http.mvcMatcher().permitAll()。 附带说明一下,我个人建议将公共页面列入白名单并向其他所有页面(例如公共文件夹)添加身份验证。这样,如果您忘记为链接添加安全性,默认情况下它是不公开的。

    【讨论】:

    • 感谢您的帮助 :) 它的工作接缝,但我打算使用“WebSecurityConfigurerAdapter”来做 JDBC 和 MySQL 的身份验证。你知道我如何在不使用它的情况下做到这一点(因为已弃用)?
    • 这个春季博客应该包含为新方法设置基本 jdbc 身份验证所需的信息。现在是周末,我手头没有代码示例spring.io/blog/2022/02/21/…
    • 再次感谢,但我认为链接中的“JDBC 身份验证”部分更多的是使用用户和密码来访问数据库,并且我想这样做可以使用使用登录我的数据库“TFE”中的“糖尿病”表中的数据。但无论如何谢谢你试图帮助我
    【解决方案2】:

    你需要告诉 Spring security 什么 URL 是公开的,像这样 -

    @Configuration
    @EnableWebSecurity
    public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
    
    private static final String[] PUBLIC_URLS = {"/public/*"};
    
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
               http.authorizeRequests()
                .antMatchers("/userOnly/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/loginPage.html");
      }
      
      @Override
      public void configure(WebSecurity web) {
        List<RequestMatcher> matchers =
        Arrays.asList(urls).stream().map(url -> new 
        AntPathRequestMatcher(url)).collect(Collectors.toList());
        web.ignoring().requestMatchers(new OrRequestMatcher(matchers));
      }
    }
    

    使用 OrRequestMatcher ,您可以创建所有需要公开的 URL 列表。 您还可以使用 NegatedRequestMatcher 获取所有私有 URL

       RequestMatcher privateUrlMatcher =  new 
       NegatedRequestMatcher(publicUrlMatcher);
    

    我还建议您将所有公共 url 保留在 /src/main/resources/static/publicui 下,并将所有私有 URL 保留在 /src/main/resources/static/privateui 下,并拥有 /publicui/* 的公共权限

    【讨论】:

      【解决方案3】:

      在您的 SecSecurityConfig 类中尝试以下操作

      @Configuration
      @EnableAutoConfiguration
      @EnableWebSecurity
      public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
      
      @Override
          protected void configure(HttpSecurity http) throws Exception {
              http.authorizeRequests()
              
                  .antMatchers("/users").authenticated()
                  .anyRequest().permitAll()
                  .and()
                  .formLogin()
                  
                      .usernameParameter("email")
                      .defaultSuccessUrl("/lib/allBooks")
                      .permitAll()
                  .and()
                  .logout().logoutSuccessUrl("/lib").permitAll();
              
              http       
              .csrf().disable();
          }
      }
      

      只需修改为您的应用程序设置的参数。如果您没有登录表单,您可以跳过

                      .usernameParameter("email")
                      .defaultSuccessUrl("/lib/allBooks")
                      .permitAll()
      

      【讨论】: