我需要为临时服务器设置全局基本 HTTP 身份验证。没有什么花哨。我只想要求用户名/密码才能访问任何内容。我也想只使用 Java 配置。我尝试了很多不同的解决方案,但都没有奏效。我总是能够访问服务器上的所有资源。这就是我现在正在做的:
@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");
}
}
我可以在日志中看到正在执行这些片段。如您所见,在第一种方法中,我要求所有请求都经过身份验证。在第二种方法中,我在内存中指定身份验证。
最佳答案
由于 @Configuration(这同样不是必需的,因为它也由 @EnableWebSecurity 声明),您的 SOP 语句正在被打印(在容器实例化时)。您仍然需要在扩展 WebMvcConfigurerAdapter 的 web.xml 或 MVC 初始化程序类中注册 spring 安全过滤器链。或实现 WebApplicationInitializer如果您希望将它与应用程序过滤器链一起使用。例如(与您正在寻找的 java 配置相同):
EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(
DispatcherType.REQUEST, DispatcherType.ERROR);
container.addFilter("springSecurityFilterChain",
DelegatingFilterProxy.class).addMappingForUrlPatterns(
dispatcherTypes, false, "/*");
其中容器是 ServletContext 的一个实例。
关于spring-mvc - Spring MVC 4 全局基本 HTTP 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30962882/