我试图让我的 Spring MVC 应用程序与 Spring @Secured 注释和 AspectJ 自动代理一起玩得很好,但它似乎没有代理或识别我的 @Secured 注释。我有一个这样的控制器:
@Controller
@RequestMapping("/")
public class ApplicationController {
private ApplicationFactory applicationFactory;
@Inject
public ApplicationController(ApplicationFactory applicationFactory) {
super();
this.applicationFactory = applicationFactory;
}
@Secured("ROLE_USER")
@ResponseBody
@RequestMapping(method = GET)
public Application getApplicationInfo() {
return applicationFactory.buildApplication(this);
}
}
还有一个看起来像这样的 Spring Security XML:
代码:
<security:global-method-security secured-annotations="enabled" mode="aspectj" proxy-target-class="true" />
<security:http auto-config="true" use-expressions="true">
<security:http-basic/>
</security:http>
上面是由一个 no-xml Spring @Configuration 组件加载的,如下所示:
@Configuration
@ComponentScan(basePackages = {"com.example"})
@EnableWebMvc
@ImportResource("classpath:security.xml")
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
}
依次使用 Servlet 3.0 WebApplicationInitializer 加载:
public class SpringMvcInitializer implements WebApplicationInitializer {
private final AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
public void onStartup(ServletContext servletContext) throws ServletException {
context.register(ApplicationConfiguration.class);
servletContext.addListener(new ContextLoaderListener(context));
servletContext.addListener(new Log4jConfigListener());
final DelegatingFilterProxy proxy = new DelegatingFilterProxy("springSecurityFilterChain", context);
FilterRegistration.Dynamic filter = servletContext.addFilter("securityFilter", proxy);
filter.addMappingForUrlPatterns(EnumSet.of(REQUEST), false, "/*");
final DispatcherServlet servlet = new DispatcherServlet(context);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", servlet);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
}
但是,Spring Security 没有检测到注释,我仍然可以在未经授权的情况下使用上面的安全端点。根据Spring Security FAQ,这可能是因为<global-method-security>
在错误的应用程序上下文中加载了元素,但我不知道如何使用上述 no-xml Spring 配置来确保这一点。
我错过了什么吗?我尝试将 @EnableAspectJAutoProxy(proxyTargetClass = true) 添加到我的应用程序配置中,但这也无济于事。无论如何有运行时编织还是我必须使用编译时编织来为我的应用程序启用基于注释的安全性?