在四处搜索并查看了许多其他示例之后,我似乎无法让Spring拦截请求。我必须没有正确配置,或者我的期望是错误的。有人能告诉我我做错了吗?
这将设置注释配置
public class WebMVCApplicationInitializer implements WebApplicationInitializer
{
@Override
public void onStartup(ServletContext servletContext) throws ServletException
{
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher =
servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
private AnnotationConfigWebApplicationContext getContext()
{
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation(String.valueOf(this.getClass().getPackage()));
return context;
}
}
My WebMvcConfig - 指定要查找带注释控制器的包
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "myproject.controller")
public class WebMvcConfig extends WebMvcConfigurerAdapter
{
}
My SecurityConfig - 应匹配并要求对所有内容进行身份验证
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated();
// @formatter:on
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
{
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
最后,我的控制器 - 只是为测试提供了一个微不足道的响应
@RestController
public class SessionController
{
@ResponseBody
@RequestMapping(value = "echo", method = RequestMethod.GET)
public Map<String, Object> testResponse()
{
Map<String, Object> modelMap = new HashMap<String, Object>();
modelMap.put("data", "test for echo");
return modelMap;
}
}
现在,我的期望是当我运行它并将浏览器指向/ echo时,它应该需要身份验证,错误或其他东西。相反,我只是得到{"data":"test for echo"}
。 (我知道我没有指定身份验证提供程序,但我至少会发现错误。)
我错过了什么?
答案 0 :(得分:0)
我需要将安全过滤器链添加到应用程序上下文中。
FilterRegistration.Dynamic security =
servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
security.addMappingForUrlPatterns(dispatcherTypes, true, "/*");