I am in the proces of creating simple CRUD program with Spring data rest Spring data rest,
but I have a problem with security configuration (example was taken from here.
I have a WebAppInitializer:
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{JpaRepositoryConfig.class, SecurityConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{CustRepositoryRestMvcConfiguration.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
return new Filter[]{ new DelegatingFilterProxy("springSecurityFilterChain")};
}
}
I have a next crud repository:
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.repository.annotation.RestResource;
import org.springframework.security.access.prepost.PreAuthorize;
#PreAuthorize("hasRole('ROLE_USER')")
#RestResource(path = "products", rel = "products")
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {
#PreAuthorize("hasRole('ROLE_ADMIN')")
#Override
Product save(Product s);
#PreAuthorize("hasRole('ROLE_ADMIN')")
#Override
void delete(Long aLong);
}
I have a next security configuration:
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("greg").password("turnquist").roles("USER").and()
.withUser("ollie").password("gierke").roles("USER", "ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/products").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT, "/products/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH, "/products/**").hasRole("ADMIN").and()
.csrf().disable();
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
I used next version of dependencies:
<java-version>1.7</java-version>
<spring-data-rest-version>1.0.0.RELEASE</spring-data-rest-version>
<spring.version>3.2.2.RELEASE</spring.version>
<org.slf4j-version>1.7.5</org.slf4j-version>
From project configured log4j I am getting these errors:
SEVERE: Error filterStart
org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/admin] startup failed due to previous errors
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationCon
text - Closing Root WebApplicationContext: startup date [Tue Dec 30 00:09:21 EET
2014]; root of context hierarchy
......
DEBUG: org.springframework.beans.factory.support.DisposableBeanAdapter - Invokin
g destroy() on bean with name 'org.springframework.security.config.annotation.au
thentication.configuration.AuthenticationConfiguration'
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Re
trieved dependent beans for bean '(inner bean)': [(inner bean), productRepositor
y]
DEBUG: org.springframework.beans.factory.support.DisposableBeanAdapter - Invokin
g destroy() on bean with name 'securityConfig'
From tomcat 7.0.56 localhost log I also have these errors in the logs:
SEVERE: Exception starting filter delegatingFilterProxy
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:568)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1102)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:278)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1121)
at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:326)
at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:236)
at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:109)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4830)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5510)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1083)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1879)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
What is causing the errors in these logs?
Related
We're running GraphQL sample Java application in WebLogic 12c, but encountered some errors with servlet during startup.
The servlet was configured and register our servlets using a ServletRegistrationBean as below:
#Configuration
#ConditionalOnWebApplication
#ConditionalOnClass(DispatcherServlet.class)
#ConditionalOnBean({GraphQLSchema.class, GraphQLSchemaProvider.class})
#ConditionalOnProperty(value = "graphql.servlet.enabled", havingValue = "true", matchIfMissing = true)
#AutoConfigureAfter({GraphQLJavaToolsAutoConfiguration.class, SpringGraphQLCommonAutoConfiguration.class})
#EnableConfigurationProperties(GraphQLServletProperties.class)
public class GraphQLWebAutoConfiguration {
...
#Bean
#ConditionalOnMissingBean
public GraphQLServlet graphQLServlet(GraphQLSchemaProvider schemaProvider, ExecutionStrategyProvider executionStrategyProvider) {
return new SimpleGraphQLServlet(schemaProvider, executionStrategyProvider, listeners, instrumentation, errorHandler, contextBuilder);
}
#Bean
ServletRegistrationBean graphQLServletRegistrationBean(GraphQLServlet servlet) {
ServletRegistrationBean bean = new ServletRegistrationBean(servlet, graphQLServletProperties.getServletMapping());
bean.setLoadOnStartup(1);
return bean;
}
}
In the weblogic server log, it prints out errors:
<Oct 2, 2017 1:51:28 PM SGT> <Error> <HTTP> <BEA-101125> <[ServletContext#933807824[app:CPRES module:CPRES path:null spec-version:3.1]] Error occurred while instantiating servlet: "simpleGraphQLServlet".
java.lang.InstantiationException: graphql.servlet.SimpleGraphQLServlet
at java.lang.Class.newInstance(Class.java:427)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:252)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:245)
at weblogic.servlet.internal.WebComponentContributor.createServletInstance(WebComponentContributor.java:274)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.newServletInstanceIfNecessary(StubSecurityHelper.java:365)
Truncated. see log file for complete stacktrace
Caused By: java.lang.NoSuchMethodException: graphql.servlet.SimpleGraphQLServlet.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:252)
at weblogic.servlet.internal.WebComponentContributor.getNewInstance(WebComponentContributor.java:245)
at weblogic.servlet.internal.WebComponentContributor.createServletInstance(WebComponentContributor.java:274)
Truncated. see log file for complete stacktrace
>
<Oct 2, 2017 1:51:28 PM SGT> <Error> <HTTP> <BEA-101216> <Servlet: "simpleGraphQLServlet" failed to preload on startup in Web application: "CPRES".
javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:326)
at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:294)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:326)
at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:196)
at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
Truncated. see log file for complete stacktrace
>
<Oct 2, 2017 1:51:29 PM SGT> <Error> <Deployer> <BEA-149265> <Failure occurred in the execution of deployment request with ID "19094957742917053" for task "130" on [partition-name: DOMAIN]. Error is: "weblogic.application.ModuleException: javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated"
weblogic.application.ModuleException: javax.servlet.ServletException: Servlet class: 'graphql.servlet.SimpleGraphQLServlet' couldn't be instantiated
It looks that the weblogic is trying to create a new servlet instance instead of the ServletBean SimpleGraphQLServlet created and managed by Spring context.
Any advance? Thanks.
A walkaround solution is to write a Servlet wrapper class like this:
public class DelegateGraphQLServlet extends HttpServlet {
protected GraphQLServlet graphQLServlet;
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
ApplicationContext ac = (ApplicationContext) servletConfig.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
this.graphQLServlet = (GraphQLServlet)ac.getBean("graphQLServlet");
}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
graphQLServlet.service(req, res);
}
}
I'm using full java based configuration for a project.
When deploying webapp, I get the following error :
Sep 06, 2016 8:13:37 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Sep 06, 2016 8:13:37 AM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Sep 06, 2016 8:13:37 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Tue Sep 06 08:13:37 CEST 2016]; root of context hierarchy
Sep 06, 2016 8:13:38 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]
Sep 06, 2016 8:13:38 AM org.springframework.web.context.ContextLoader initWebApplicationContext
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:612)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:513)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4813)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5272)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/net.brewspberry.util.SpringWebappConfiguration]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 21 more
The thing is I don't get why Spring tries to load an XML config while I registered a Class config :
WebappInitializer :
package net.brewspberry.util.config;
import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import net.brewspberry.filters.AuthentificationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringWebappInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer implements
WebApplicationInitializer {
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.setServletContext(servletContext);
// rootContext.setConfigLocation("net.brewspberry.util");
rootContext.register(SpringCoreConfiguration.class);
servletContext.addListener(new ContextLoaderListener(rootContext));
// now the config for the Dispatcher servlet
AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
// mvcContext.setConfigLocation("net.brewspberry.util.config");
//mvcContext.register(SpringWebappConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"DispatcherServlet", new DispatcherServlet(mvcContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.do");
}
#Override
protected Filter[] getServletFilters() {
return null; // new Filter[] { new AuthentificationFilter() };
}
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return null;
}
}
Webapp config :
package net.brewspberry.util.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan({ "net.brewspberry" })
public class SpringWebappConfiguration extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/login.jsp");
}
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
I have no web.xml necesary as WebAppInitializer replaces it. I tried with or without that line :
mvcContext.register(SpringWebappConfiguration.class);
but it does not change anything.
Moreover, in logs, Spring searches for XML application context while in initializer it is defined as an annotation application context. I don't get it...
Any idea ?
You have to specify dispatcher servlet to use SpringWebappConfiguration as it context or set SpringWebappConfiguration as applicationRoot context.
I am trying to integrate spring security using java configuration for couple of days with no luck and it got my brains out figuring what's going wrong. Really looking for some help here.
The java files i have used for the configuration are AppConfig.java, SecurityConfig.java, SpringAnnotationWebInitializer.java SpringSecurityInitializer.java, AppInitializer.java and web.xml is also there. I am listing the code for each file below.
First of all web.xml
<web-app>
<!-- <context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param> -->
<!-- Bootstrap the root application context as usual using ContextLoaderListener -->
<!-- <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> -->
<servlet>
<servlet-name>spring-dispatcher</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>backend.configuration.AppConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
Next is SecurityConfig.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
try {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
Next SpringSecurityInitializer.java
#Order(1)
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer{
}
SpringAnnotationWebInitializer.java
public class SpringAnnotationWebInitializer extends AbstractContextLoaderInitializer {
#Override
protected WebApplicationContext createRootApplicationContext() {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(AppConfig.class);
return applicationContext;
}
}
AppConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "backend")
#Import({SecurityConfig.class})
public class AppConfig extends WebMvcConfigurerAdapter {
#Bean
public ResourceBundleViewResolver resourceBundleViewResolver() {
ResourceBundleViewResolver resolver = new ResourceBundleViewResolver();
resolver.setBasename("messages");
resolver.setOrder(0);
return resolver;
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/static/");
viewResolver.setSuffix(".html");
viewResolver.setOrder(1);
return viewResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("/static/");
}
}
Finally AppInitializer.java
public class AppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet(
"dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
FilterRegistration.Dynamic filter = ctx.getServletContext().addFilter(
"springSecurityFilterChain", new DelegatingFilterProxy());
filter.addMappingForUrlPatterns(null, false, "/*");
}
}
When I run this application on tomcat I am getting the following NullPointer Exception
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:188)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:799)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
... 6 more
Caused by: java.lang.NullPointerException
at backend.configuration.AppInitializer.onStartup(AppInitializer.java:33)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5456)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more
Sep 14, 2015 8:11:11 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:188)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:731)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:799)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more
at the following line in AppInitializer.java
filter.addMappingForUrlPatterns(null, false, "/*");
I think I am not able to initialize the security filter. I have tried the following links for the solution but was not able to get any success. I am definitely missing something.
NullPointerException at org.springframework.security.web.FilterChainProxy.getFilters
springSecurityFilterChain nullPointer Exception
I have tried lot of other links as well but still stuck. Please help me out here
Finally, able to fix now. Need to change the two files - SpringAnnotationWebInitializer.java and AppInitializer.java
Changed the SpringAnnotationWebInitializer.java to extend "AbstractAnnotationConfigDispatcherServletInitializer" instead of "AbstractContextLoaderInitializer" and removed the servlet and filter initialization from AppInitializer.java
So the final code for these two files is as follows:
SpringAnnotationWebInitializer.java
public class SpringAnnotationWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return null;
}
}
AppInitializer.java
public class AppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(container);
}
}
Finally, the basic spring security is integrated (phewww). I hope this will help others, as this has all the configuration(except maven dependencies) that is needed to integrate the basic spring-security using java configuration into your app.
I really need your help to solve this problem... I'm working with Spring-MVC 4.1.6.RELEASE, Spring-Security 4.0.0.RELEASE
I'm having this ERROR just... "sometimes" when I start the server. That's the real problem it just happens sometimes.
java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:252)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Then you will say, that's easy you just have to add a ContextLoaderListener but when I do, I get this:
java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!
But it is not always... So I guess there is something wrong in the order that the context are being initialized but I don't know how to fix it...
These are my configuration classes:
WebInitializer.java
public class WebInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(ServerApplicationConfig.class);
servletContext.addListener(new RequestContextListener());
servletContext.addListener(new ContextLoaderListener(rootContext));
FacesServlet facesServlet = new FacesServlet();
ServletRegistration.Dynamic facesServletDynamic = servletContext.addServlet("facesServlet", facesServlet);
facesServletDynamic.addMapping("*.jsf");
facesServletDynamic.setLoadOnStartup(1);
servletContext.addListener(ConfigureListener.class);
//Oauth2Filter
servletContext.addFilter("auth2ClientContextFilter", OAuth2ClientContextFilter.class);
}
}
ServerApplicationConfig.java
#EnableWebMvc
#Import({ WebSecurityConfig.class, HibernateConfig.class })
#ComponentScan(basePackages = { "com.agrichem.server" }, scopedProxy = ScopedProxyMode.TARGET_CLASS)
#Configuration
public class ServerApplicationConfig {
#Bean
public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() {
TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ClassPathResource[] resources = new ClassPathResource[] {
new ClassPathResource("jdbc.properties"),
new ClassPathResource("oada-client.properties") };
ppc.setLocations(resources);
return ppc;
}
#Bean
#Qualifier("viewResolver")
public ViewResolver getViewResolver() {
UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
viewResolver.setViewClass(JsfView.class);
viewResolver.setPrefix("/views/");
viewResolver.setSuffix(".xhtml");
return viewResolver;
}
}
WebSecurityInitializer.java
#Configuration
#Order(1)
public class WebSecurityInitializer extends
AbstractSecurityWebApplicationInitializer {
}
WebSecurityConfig.java
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
#Qualifier("customUserDetailsService")
private UserDetailsService customUserDetailsService;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(customUserDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.logout().logoutUrl("/logout.jsf").permitAll()
.logoutSuccessUrl("/home/login.jsf");
http.authorizeRequests()
.antMatchers("*.css", "*.js", "**.gif", "*.jpg", "*.jpeg",
"*.png", "*.css.jsf", "*.js.jsf", "**.gif.jsf",
"*.jpg.jsf", "*.jpeg.jsf", "*.png.jsf")
.permitAll()
.antMatchers("/**/*.css", "/**/*.js", "/**/*.gif", "/**/*.jpg",
"/**/*.jpeg", "/**/*.png", "/**/*.css.jsf",
"/**/*.js.jsf", "/**/*.gif.jsf", "/**/*.jpg.jsf",
"/**/*.jpeg.jsf", "/**/*.png.jsf")
.permitAll()
.antMatchers("/**/*.woff2", "/**/*.eot", "/**/*.woff",
"/**/*.ttf", "/**/*.svg", "*.woff2", "*.eot", "*.woff",
"*.ttf", "*.svg", "/**/*.woff2.jsf", "/**/*.eot.jsf", "/**/*.woff.jsf",
"/**/*.ttf.jsf", "/**/*.svg.jsf", "*.woff2.jsf", "*.eot.jsf", "*.woff.jsf",
"*.ttf.jsf", "*.svg.jsf")
.permitAll();
http.authorizeRequests().antMatchers("/admin/**.jsf").hasRole("ADMIN");
// http.authorizeRequests().antMatchers("/farms/**.jsf").hasAnyRole("HEAD_OFFICER");
http.authorizeRequests().antMatchers("/home/logout.jsf").permitAll()
.antMatchers("/rest/**").permitAll();
http.authorizeRequests().anyRequest().authenticated().and().formLogin()
.loginPage("/home/login.jsf").permitAll()
.failureUrl("/home/login.jsf?error=denied").permitAll()
.defaultSuccessUrl("/home/index.jsf", true);
}
}
Thanks for your help in advance.
I am trying to add Spring security with customized login page and access to database to my Spring MVC application. It seems like my mapping is wrong as it can not map j_spring_security_check.
To solve the issue I had a look at following pages 1,2,3 but could not solve the issue yet.
If you do not have much time, please read PART 2 below, that is where edited section of the question begins. Otherwise, please read both PART 1 and PART 2.
PART 1
I also added following lines to my web.xml file but the application returns following exceptions.
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Caused by: java.lang.IllegalStateException: Duplicate Filter registration for 'springSecurityFilterChain'. Check to ensure the Filter is only configured once.
at org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer.registerFilter(AbstractSecurityWebApplicationInitializer.java:215)
at org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer.insertSpringSecurityFilterChain(AbstractSecurityWebApplicationInitializer.java:147)
at org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer.onStartup(AbstractSecurityWebApplicationInitializer.java:121)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5423)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more
Jun 13, 2015 2:44:54 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:188)
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.startup.Catalina.start(Catalina.java:691)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:456)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more
Jun 13, 2015 2:44:54 PM org.apache.catalina.startup.Catalina start
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.startup.Catalina.start(Catalina.java:691)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:456)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 11 more
Without adding that filter once the form is submitted the request will be catch by following controller.
#Controller
public class MainController {
#RequestMapping("/{viewName}")
public String index(#PathVariable String viewName) {
...
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<listener>
<listener-class>org.apache.tiles.extras.complete.CompleteAutoloadTilesListener</listener-class>
</listener>
<servlet>
<servlet-name>my</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- <listener> -->
<!-- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> -->
<!-- </listener> -->
<!-- <filter> -->
<!-- <filter-name>springSecurityFilterChain</filter-name> -->
<!-- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> -->
<!-- </filter> -->
<!-- <filter-mapping> -->
<!-- <filter-name>springSecurityFilterChain</filter-name> -->
<!-- <url-pattern>/*</url-pattern> -->
<!-- </filter-mapping> -->
<servlet-mapping>
<servlet-name>my</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/my-security.xml
</param-value>
</context-param>
</web-app>
my-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<http auto-config="true" access-denied-page="/notFound.jsp"
use-expressions="true">
<intercept-url pattern="/" access="permitAll" />
</http>
<!-- <beans:import resource="security-db.xml" /> -->
<authentication-manager>
<authentication-provider>
<user-service>
<user name="alex" password="123456" authorities="ROLE_USER" />
<user name="mkyong" password="123456" authorities="ROLE_USER, ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
AppConfig.java
#EnableWebMvc
#Configuration
#ComponentScan({ "com.myproject.*" })
#EnableTransactionManagement
#Import({ SecurityConfig.class })
public class AppConfig {
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(
dataSource());
builder.scanPackages("com.myproject.model").addProperties(
getHibernateProperties());
return builder.buildSessionFactory();
}
private Properties getHibernateProperties() {
Properties prop = new Properties();
prop.put("hibernate.format_sql", "true");
prop.put("hiberate.show_sql", "true");
prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return prop;
}
#Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/test");
ds.setUsername("jack");
ds.setPassword("jack");
return ds;
}
#Bean
public HibernateTransactionManager txManager() {
return new HibernateTransactionManager(sessionFactory());
}
}
SecurityConfig.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
#Qualifier("userDetailsService")
UserDetailsService userDetailsService;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(
passwordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/profile/**")
.access("hasRole('ADMIN')").and().formLogin()
.loginPage("/signin").failureUrl("/signin?error")
.usernameParameter("username").passwordParameter("password")
.and().logout().logoutSuccessUrl("/index").and().csrf().and()
.exceptionHandling().accessDeniedPage("/403");
}
#Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
SpringMVCInitializer.java
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
LoginController.java
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}
}
**
PART 2
Based on Thomas's suggestions I changed the code as following
**
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<listener>
<listener-class>org.apache.tiles.extras.complete.CompleteAutoloadTilesListener</listener-class>
</listener>
<servlet>
<servlet-name>my</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>my</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
AppConfig.java
#EnableWebMvc
#Configuration
#ComponentScan({ "com.myproject" })
#EnableTransactionManagement
#Import({ SecurityConfig.class })
public class AppConfig {
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(
dataSource());
builder.scanPackages("com.myproject.model").addProperties(
getHibernateProperties());
return builder.buildSessionFactory();
}
private Properties getHibernateProperties() {
Properties prop = new Properties();
prop.put("hibernate.format_sql", "true");
prop.put("hiberate.show_sql", "true");
prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return prop;
}
#Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/test");
ds.setUsername("jack");
ds.setPassword("jack");
return ds;
}
#Bean
public HibernateTransactionManager txManager() {
return new HibernateTransactionManager(sessionFactory());
}
}
SecurityConfig.java
#Configuration
#EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
#Qualifier("userDetailsService")
UserDetailsService userDetailsService;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
// auth.userDetailsService(userDetailsService).passwordEncoder(
// passwordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/profile/**")
.access("hasRole('ADMIN')").and().formLogin()
.loginPage("/login").failureUrl("/login?error")
.and().logout().logoutSuccessUrl("/index").and().csrf().and()
.exceptionHandling().accessDeniedPage("/403");
}
#Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
SpringMVCInitializer.java
public class SpringMvcInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
MainController
#Controller
public class MainController {
#RequestMapping("/{viewName}")
public String index(#PathVariable String viewName) {
System.err.println("View Name is :" + viewName);
if (isValidView(viewName)) {
return viewName;
}
return null;
}
Regarding MainController, this is the way that I handle static pages such as www.myproject.com/index, www.myproject.com/contactus etc. My other question regarding this issue is here
There are several issues in your code. The most important one is that you are mixing the Java configuration and the XML configuration for Spring Security. Decide which configuration you prefer to use. In my answer, I will focus on the Java-based configuration, as I would completely remove the XML configuration from your code.
In your case, the #EnableWebSecurity annotation by default already registers the appropriate filters. But if your are using the Spring MVC, it should rather be #EnableWebMvcSecurity.
Furthermore, look at your HttpSecurity configuration:
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/profile/**")
.access("hasRole('ADMIN')").and().formLogin()
.loginPage("/signin").failureUrl("/signin?error")
.usernameParameter("username").passwordParameter("password")
.and().logout().logoutSuccessUrl("/index").and().csrf().and()
.exceptionHandling().accessDeniedPage("/403");
}
You are obviously telling that login page will be at /signin, but in your LoginController the mapping is for /login. And what for you config the .usernameParameter("username") .passwordParameter("password")? It's already done this way in Spring Security default configuration.
You should also add the SecurityInitializer class, which in Spring Security 3.2 can look like this:
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
public SecurityInitializer() {
super(SecurityConfig.class);
}
}
So to sum up, the basic steps to add the Spring Security to your project is to do the following:
Add the appropriate (Maven, Gradle) dependencies for Spring Security;
Configure the Spring Security class annotated with #EnableWebMvcSecurity, especially in configureGlobal(...) and configure(...) methods;
Register the class extending AbstractSecurityWebApplicationInitializer;
Provide the mapping for login page in your controller and write down the custom form in JSP page.
The basic login form can look like this:
<form name='loginForm' method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" /></td>
</tr>
</table>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
These basic steps enable the Spring Security in your project. For more information, the good tutorials are:
http://docs.spring.io/spring-security/site/docs/3.2.x/guides/hellomvc.html
http://docs.spring.io/spring-security/site/docs/3.2.x/guides/form.html
Good luck :)
I would highly suggest you to follow either Java or XML config. I personally prefer Java config.
Remove all Spring Security related XML configs and create following
files.
Amend the permission addresses to whatever you have.
public class MessageSecurityWebApplicationInitializer extends
AbstractSecurityWebApplicationInitializer { //register the springSecurityFilterChain with the war
}
public class MessageWebApplicationInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SecurityConfig.class }; //make sure your config file gets loaded
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return null;
}
#Configuration
#EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
System.err.println("in here");
auth.inMemoryAuthentication().withUser("user#yahoo.com")
.password("password").roles("USER"); //access to inmemory credentials
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/**", "/", "/index", "/aboutus")
.permitAll() //allow access to your static pages and resources
.antMatchers("/profile/**")
.hasRole("USER") //profile address is only available to users ( do not need to add ROLE_ as Spring does it for you)
.and() //and is equivalent of end tag in XML
.formLogin().loginPage("/signin").failureUrl("/signin?error")
.permitAll().and().logout().logoutUrl("/singout").permitAll();
}
For further explanation and to access to DB refer to the documentation