使用Spring Security Java配置时禁用基本身份验证

问题描述 投票:13回答:5

我正在尝试使用Spring Security java配置来保护Web应用程序。

这是配置的外观: -

@Configuration
@EnableWebMvcSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private String googleClientSecret;

    @Autowired
    private CustomUserService customUserService;

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.security.config.annotation.web.configuration.
     * WebSecurityConfigurerAdapter
     * #configure(org.springframework.security.config
     * .annotation.web.builders.HttpSecurity)
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // @formatter:off
        http
            .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/","/static/**", "/resources/**","/resources/public/**").permitAll()
                .anyRequest().authenticated()
            .and()
                .formLogin()
                    .and()
                .httpBasic().disable()
            .requiresChannel().anyRequest().requiresSecure();
        // @formatter:on
        super.configure(http);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        // @formatter:off
        auth
            .eraseCredentials(true)
            .userDetailsService(customUserService);
        // @formatter:on
        super.configure(auth);
    }
}

请注意,我已使用以下方法明确禁用HTTP基本身份验证:

.httpBasic().disable()

访问安全URL时,我仍然收到HTTP身份验证提示框。为什么?

请帮我解决这个问题。我只想渲染捆绑的默认登录表单。

Spring Boot Starter版本:1.1.5 Spring Security版本:3.2.5

谢谢

spring-security spring-boot spring-java-config
5个回答
19
投票

首先,调用super.configure(http);将覆盖您之前的整个配置。

试试这个:

http
    .authorizeRequests()
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .and()
    .httpBasic().disable();

6
投票

如果你使用Spring Boot,documentation说:

要在Web应用程序中完全关闭Boot默认配置,您可以添加带有@EnableWebSecurity的bean

因此,如果您想完全自定义可能是一个选项。

只是为了说清楚......你只需要在主应用程序类或应用程序配置类上放置@EnableWebSecurity注释。


4
投票

您可以通过HttpSecurity实例禁用formLogin,如下所示:

http.authorizeRequests().antMatchers("/public/**").permitAll()
        .antMatchers("/api/**").hasRole("USER")
        .anyRequest().authenticated() 
        .and().formLogin().disable();

这将导致在尝试访问任何安全资源时收到403 Http错误


2
投票

匿名选项对我有用。我的代码就像

  http.csrf().disable().headers().frameOptions().sameOrigin().and().
   authorizeRequests().anyRequest().anonymous().and().httpBasic().disable();

-6
投票

以下对我有用:

            http
                .authorizeRequests()
                .anyRequest().permitAll();
© www.soinside.com 2019 - 2024. All rights reserved.