2

我需要为登台服务器设置全局基本HTTP身份验证。没有什么花哨。我只想要求用户名/密码来访问任何东西。我也只想使用Java配置。我已经尝试了很多不同的解决方案,但都没有工作。我总是能够访问服务器上的所有资源。这是我现在在做什么:Spring MVC 4全局基本HTTP身份验证

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
    System.out.println("Configuring HttpSecurity"); 

    http 
      .authorizeRequests() 
      .anyRequest().authenticated() 
      .and() 
      .httpBasic(); 
    } 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
    System.out.println("Configuring global AuthenticationManagerBuilder"); 

    auth 
      .inMemoryAuthentication() 
      .withUser("user").password("password").roles("USER"); 
    } 
} 

我可以在正在执行这些片段中的日志中看到。如您所见,在第一种方法中,我要求所有请求都经过身份验证。在第二种方法中,我在内存认证中指定。

+0

你得到的错误是什么?还有你是如何尝试登录的?需要更多的信息给问题 – ArunM

+0

没有错误。问题是我没有提示执行基本的HTTP身份验证。每当请求任何资源时,我都希望始终需要基本的HTTP身份验证。 –

回答

0

由于@Configuration(由于它也是由@EnableWebSecurity声明,因此不再需要)您的SOP语句正在打印(而容器实例化)。如果您希望将其与应用程序过滤器链一起使用,您仍然需要在web.xml或MVC初始化程序类中注册spring安全过滤器链,该类可扩展WebMvcConfigurerAdapter或实现WebApplicationInitializer。例如(java配置,因为你正在寻找相同的):

EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(
      DispatcherType.REQUEST, DispatcherType.ERROR); 
container.addFilter("springSecurityFilterChain", 
      DelegatingFilterProxy.class).addMappingForUrlPatterns(
      dispatcherTypes, false, "/*"); 

其中容器是一个ServletContext的实例。