使用maven添加Spring Spring 4.0.0版本的Spring安全框架3.2.3。 问题是应该进行身份验证的页面不会丢弃任何登录表单而是显示内容。
web.xml -
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SpringMvcJdbcTemplate</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.wiselife.in</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
WebMVCConfiguration(基于注释)
@Configuration
@ComponentScan(basePackages="com.wiselife.in")
@EnableWebMvc
@Import({ AppSecurityConfig.class })
public class MvcConfiguration extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
/*public @Bean TilesViewResolver tilesViewResolver() {
return new TilesViewResolver();
}
public @Bean TilesConfigurer tilesConfigurer() {
TilesConfigurer ret = new TilesConfigurer();
ret.setDefinitions(new String[] { "/WEB-INF/tiles-defs.xml" });
return ret;
}*/
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/contactdb");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
@Bean
public ContactDAO getContactDAO() {
return new ContactDAOImpl(getDataSource());
}
AppSecurityConfig: -
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("tom").password("123456")
.roles("USER");
auth.inMemoryAuthentication().withUser("bill").password("123456")
.roles("ADMIN");
auth.inMemoryAuthentication().withUser("james").password("123456")
.roles("SUPERADMIN");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("tom").password("123456").roles("USER").and()
.withUser("bill").password("123456").roles("USER", "ADMIN").and()
.withUser("james").password("123456").roles("USER", "ADMIN", "SUPERADMIN");
}
@Bean @Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/protected/**")
.access("hasRole('ROLE_ADMIN')")
.antMatchers("/confidential/**")
.access("hasRole('ROLE_SUPERADMIN')").and().formLogin();
}
主控制器: -
@Controller
public class HomeController {
@Autowired
private ContactDAO contactDAO;
@RequestMapping(value = "/")
public ModelAndView listContact(ModelAndView model) throws IOException {
List<Contact> listContact = contactDAO.list();
model.addObject("listContact", listContact);
model.setViewName("home");
return model;
}
@RequestMapping(value = "/newContact", method = RequestMethod.GET)
public ModelAndView newContact(ModelAndView model) {
Contact newContact = new Contact();
model.addObject("contact", newContact);
model.setViewName("ContactForm");
return model;
}
@RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(@ModelAttribute Contact contact) {
contactDAO.saveOrUpdate(contact);
return new ModelAndView("redirect:/");
}
@RequestMapping(value = "/deleteContact", method = RequestMethod.GET)
public ModelAndView deleteContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
contactDAO.delete(contactId);
return new ModelAndView("redirect:/");
}
@RequestMapping(value = "/protected**", method = RequestMethod.GET)
public ModelAndView protectedPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security 3.2.3 Hello World");
model.addObject("message",
"This is protected page - Only for Administrators !");
model.setViewName("protected");
return model;
}
@RequestMapping(value = "/confidential**", method = RequestMethod.GET)
public ModelAndView superAdminPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security 3.2.3 Hello World");
model.addObject("message",
"This is confidential page - Need Super Admin Role !");
model.setViewName("protected");
return model;
}
@RequestMapping(value = "/editContact", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
Contact contact = contactDAO.get(contactId);
ModelAndView model = new ModelAndView("ContactForm");
model.addObject("contact", contact);
return model;
}
这里的任何帮助都会非常明显。 AJ
答案 0 :(得分:0)
Spring的网络安全配置存在一个非常棘手的陷阱:您必须 使用@EnableWebSecurity
或对其进行注释extends WebSecurityConfigurerAdapter
。当您同时拥有这两者时,默认值@EnableWebSecurity
优先,并且您的自定义配置将被忽略。因此,我希望您的应用程序在删除注释时开始表现良好。
你似乎没有使用每个控制器方法的安全注释,我建议你删除@EnableGlobalMethodSecurity(securedEnabled = true)
注释,它只用于使其工作。在这种情况下,您不需要configureGlobal
方法。它甚至可能与您的configure
方法发生冲突。