Версия Spring 4.0.0 с весенней защитной картой 3.2.3 добавлена с использованием maven. Проблема заключается в том, что страницы, которые должны быть аутентифицированы, не выбрасывают какую-либо форму входа и скорее показывают контент.Аутентификация и авторизация не работают для весны 4.0
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
Как было предложено, я редактировал класс AppSecurityConfig и удален как аннотации @EnableWebSecurity @EnableGlobalMethodSecurity (securedEnabled = истинный) также удалить функцию configureGlobal, но теперь мое приложение дает мне некоторые ошибки, связанным с автоматическим связыванием - орга. springframework.beans.factory.BeanCreationException: ошибка при создании bean-компонента с именем «appSecurityConfig»: не удалось выполнить инъекцию автоуведомленных зависимостей; вложенные exc ... Извините за глупые вопросы, но серьезно новые для весны. – AJ84
Сокровенное вложенное исключение объясняет, что действительно не удалось. –