Main Tutorials

Spring Security Hello World Annotation Example

security

In preview post, we are using XML files to configure the Spring Security in a Spring MVC environment. In this tutorial, we are going to show you how to convert the previous XML-base Spring Security project into a pure Spring annotation project.

Technologies used :

  1. Spring 3.2.8.RELEASE
  2. Spring Security 3.2.3.RELEASE
  3. Eclipse 4.2
  4. JDK 1.6
  5. Maven 3
  6. Tomcat 7 (Servlet 3.x)

Few Notes

  1. This tutorial is using WebApplicationInitializer to load the Spring Context Loader automatically, which is supported in Servlet 3.x container only, for example, Tomcat 7 and Jetty 8.
  2. Since we are using WebApplicationInitializer, the web.xml file is NOT required.
  3. Spring Security annotations are supported in older Servlet 2.x container, for example, Tomcat 6. If you use the classic XML file to load the Spring context, this tutorial is still able to deploy on Servlet 2.x container, for example, Tomcat 6

1. Project Demo

See how it works.

2. Directory Structure

Review the final directory structure of this tutorial.

spring-security-helloworld-annotation-directory

3. Spring Security Dependencies

To use Spring security, you need spring-security-web and spring-security-config.

pom.xml

	<properties>
		<jdk.version>1.6</jdk.version>
		<spring.version>3.2.8.RELEASE</spring.version>
		<spring.security.version>3.2.3.RELEASE</spring.security.version>
		<jstl.version>1.2</jstl.version>
	</properties>

	<dependencies>

		<!-- Spring 3 dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>${spring.security.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${spring.security.version}</version>
		</dependency>

		<!-- jstl for jsp page -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>

	</dependencies>

4. Spring MVC Web Application

A simple controller :

  1. If URL = /welcome or / , return hello page.
  2. If URL = /admin , return admin page.
  3. If URL = /dba , return admin page.

Later, we will secure the /admin and /dba URLs.

HelloController.java

package com.mkyong.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {

	@RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
	public ModelAndView welcomePage() {

		ModelAndView model = new ModelAndView();
		model.addObject("title", "Spring Security Hello World");
		model.addObject("message", "This is welcome page!");
		model.setViewName("hello");
		return model;

	}

	@RequestMapping(value = "/admin**", method = RequestMethod.GET)
	public ModelAndView adminPage() {

		ModelAndView model = new ModelAndView();
		model.addObject("title", "Spring Security Hello World");
		model.addObject("message", "This is protected page - Admin Page!");
		model.setViewName("admin");

		return model;

	}

	@RequestMapping(value = "/dba**", method = RequestMethod.GET)
	public ModelAndView dbaPage() {

		ModelAndView model = new ModelAndView();
		model.addObject("title", "Spring Security Hello World");
		model.addObject("message", "This is protected page - Database Page!");
		model.setViewName("admin");

		return model;

	}

}

Two JSP pages.

hello.jsp

<%@page session="false"%>
<html>
<body>
	<h1>Title : ${title}</h1>	
	<h1>Message : ${message}</h1>	
</body>
</html>
admin.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>
<html>
<body>
	<h1>Title : ${title}</h1>
	<h1>Message : ${message}</h1>

	<c:if test="${pageContext.request.userPrincipal.name != null}">
		<h2>Welcome : ${pageContext.request.userPrincipal.name} 
                 | <a href="<c:url value="/logout" />" > Logout</a></h2>  
	</c:if>
</body>
</html>

5. Spring Security Configuration

5.1 Create a Spring Security configuration file, and annotated with @EnableWebSecurity

SecurityConfig.java

package com.mkyong.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
	  auth.inMemoryAuthentication().withUser("mkyong").password("123456").roles("USER");
	  auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
	  auth.inMemoryAuthentication().withUser("dba").password("123456").roles("DBA");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {

	  http.authorizeRequests()
		.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
		.antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
		.and().formLogin();
		
	}
}

The equivalent of the Spring Security xml file :


	<http auto-config="true">
		<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
		<intercept-url pattern="/dba**" access="ROLE_ADMIN,ROLE_DBA" />
	</http>

	<authentication-manager>
	  <authentication-provider>
	    <user-service>
		<user name="mkyong" password="123456" authorities="ROLE_USER" />
		<user name="admin" password="123456" authorities="ROLE_ADMIN" />
		<user name="dba" password="123456" authorities="ROLE_DBA" />
	    </user-service>
	  </authentication-provider>
	</authentication-manager>

5.2 Create a class extends AbstractSecurityWebApplicationInitializer, it will load the springSecurityFilterChain automatically.

SpringSecurityInitializer.java

package com.mkyong.config.core;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
   //do nothing
}

The equivalent of Spring Security in web.xml file :


	<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>

6. Spring MVC Configuration

6.1 A Config class, define the view’s technology and imports above SecurityConfig.java.

AppConfig.java

package com.mkyong.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan({ "com.mkyong.web.*" })
@Import({ SecurityConfig.class })
public class AppConfig {

	@Bean
	public InternalResourceViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver 
                          = new InternalResourceViewResolver();
		viewResolver.setViewClass(JstlView.class);
		viewResolver.setPrefix("/WEB-INF/pages/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
	
}

The equivalent of the Spring XML file :


	<context:component-scan base-package="com.mkyong.web.*" />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

6.2 Create a Initializer class, to load everything.

SpringMvcInitializer.java

package com.mkyong.config.core;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.mkyong.config.AppConfig;

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[] { "/" };
	}
	
}

Done.

Note
In Servlet 3.x container environment + Spring container will detect and loads the Initializer classes automatically.

7. Demo

7.1. Welcome Page – http://localhost:8080/spring-security-helloworld-annotation/welcome

spring-security-helloworld-annotation-welcome

7.2 Try to access /admin page, Spring Security will intercept the request and redirect to /login, and a default login form is displayed.

spring-security-helloworld-annotation-login

7.3. If username and password is incorrect, error messages will be displayed, and Spring will redirect to this URL /login?error.

spring-security-helloworld-annotation-login-error

7.4. If username and password is correct, Spring will redirect the request to the original requested URL and display the page.

spring-security-helloworld-annotation-admin

7.5. For unauthorized user, Spring will display the 403 access denied page. For example, user “mkyong” or “dba” try to access the /admin URL.

spring-security-helloworld-annotation-403

Download Source Code

References

  1. Spring Security
  2. Spring Security Java Config Preview: Web Security
  3. Hello Spring MVC Security Java Config
  4. Wikipedia : Java Servlet
  5. Wikipedia : Apache Tomcat
  6. Spring Security Hello World XML Example

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
51 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Chris Linder
8 years ago

help WARNING: No mapping found for HTTP request with URI [/SecurityMVC/welcome] in DispatcherServlet with name ‘dispatcher’

Mike H
9 years ago

I had to change two things to get this to work:

Add this to the maven pom.xml (if copying from the web page)…

javax.servlet
javax.servlet-api
3.1.0
provided

The example in the zip file has this except there is a typo: replace ‘provider’ with ‘provided’ in the scope tag.

Secondly, the WAR plug-in doesn’t like not having a web.xml file, so I added this to the config in the pom.xml:

org.apache.maven.plugins
maven-war-plugin

false

After that it worked fine on Tomcat 8 with Java 1.8.

krishnan
4 years ago
Reply to  Mike H

thanks really helped

Babar
5 years ago
Reply to  Mike H

it worked for me too thanks

Vishnudev K
8 years ago
Reply to  Mike H

why there is no web.xml? When i tried it with web.xml its not working. 🙁

Yogesh
6 years ago

I am getting the following error while executing this porgram:
“getServletConfigClasses() did not return any configuration classes”

Can somebody help me understand this?

Andrew
9 years ago

I’ve made all of the suggested changes and I continue to get the following 404 error

HTTP Status 404 – /spring-security-helloworld-annotation/

type Status report

message /spring-security-helloworld-annotation/

description The requested resource is not available.

Apache Tomcat/8.0.15

see more 0 You must sign in to down-vote this post.

pratap
4 years ago
Reply to  Andrew

it is not supported in tomcat 8 and later versions …….try with tomcat 7

WILLIANS MARTINS DE MORAES
5 years ago
Reply to  Andrew

Here works fine, when I put in “deployment assembly” the maven dependencies. 😉 tks mkyong

Babar
5 years ago

i am a newbie
getting same error
can you please help me out how do you solve this issue

Loc Le
6 years ago

auth.inMemoryAuthentication().withUser(“mkyong”).password(“123456”).roles(“USER”);
auth.inMemoryAuthentication().withUser(“admin”).password(“123456”).roles(“ADMIN”);
auth.inMemoryAuthentication().withUser(“dba”).password(“123456”).roles(“DBA”);

How can I using username and password get from database?

Javed
6 years ago

I am getting this error..

[ERROR] COMPILATION ERROR :
[INFO] ————————————————————-
[ERROR] MY-WorkSpacesspring-security-helloworld-annotationssrcmainjavacommkyongconfigcoreSpringSecurityInitializer.java:[5,7] error: cannot access ServletException
[ERROR] MY-WorkSpacesspring-security-helloworld-annotationssrcmainjavacommkyongconfigSecurityConfig.java:[12,7] error: cannot access Filter
[INFO] 2 errors
[INFO] ————————————————————-
[INFO] ————————————————————————
[INFO] BUILD FAILURE
[INFO] ————————————————————————
[INFO] Total time: 2.371 s
[INFO] Finished at: 2017-05-19T15:22:21+05:30
[INFO] Final Memory: 11M/27M
[INFO] ————————————————————————
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project spring-security-helloworld-annotations: Compilation failure: Compilation failure:
[ERROR] MY-WorkSpacesspring-security-helloworld-annotationssrcmainjavacommkyongconfigcoreSpringSecurityInitializer.java:[5,7] error: cannot access ServletException
[ERROR] MY-WorkSpacesspring-security-helloworld-annotationssrcmainjavacommkyongconfigSecurityConfig.java:[12,7] error: cannot access Filter
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project spring-security-helloworld-annotations: Compilation failure
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.CompilationFailureException: Compilation failure
at org.apache.maven.plugin.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:656)
at org.apache.maven.plugin.CompilerMojo.execute(CompilerMojo.java:128)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
… 20 more

Pascal Baumans
7 years ago

It’s a pitty to wrote such a promessing sample that finally does not work out of the box.

Kirill Turutin
8 years ago

It would be just awesome if you provide an example with custom Login page!
Thank you!

Did not compile
9 years ago

I have the same problem. Did not compile

Dmitry White
5 years ago

Omg, thank you!
I have created the same structure as you did and now my springSecurity started to work!
I spened 2 days… =)

praveen parihar
5 years ago

hiiii i got error while runing the project

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘springSecurityFilterChain’ defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/web/filter/CorsFilter
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1094)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:989)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5155)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5680)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1702)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1692)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.servlet.Filter org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain() throws java.lang.Exception] threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/web/filter/CorsFilter
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
… 25 more
Caused by: java.lang.NoClassDefFoundError: org/springframework/web/filter/CorsFilter
at org.springframework.security.config.annotation.web.builders.FilterComparator.(FilterComparator.java:74)
at org.springframework.security.config.annotation.web.builders.HttpSecurity.(HttpSecurity.java:121)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:178)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:290)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:67)
at com.spring.SecurityConfig$$EnhancerBySpringCGLIB$$10da8f75.init()
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371)
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325)
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$622fd62d.CGLIB$springSecurityFilterChain$0()
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$622fd62d$$FastClassBySpringCGLIB$$683cc49f.invoke()
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$622fd62d.springSecurityFilterChain()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
… 26 more

molly
6 years ago

Hi,

I download this project. When I attempted to access admin page and login as admin. It redirects to home page not admin page. How to solve it?

vijaya
5 years ago
Reply to  molly

use@RequestMapping(value = “/admin”, method = RequestMethod.GET) instead of @RequestMapping(value = “/admin**”, method = RequestMethod.GET) while debugging i got to know that url mapping is diiferent. but after that getting jasper exception even though we are passing jstl 1.2 jar, if you have any idea on this help me on this

Vishnudev K
8 years ago

There is no web.xml in the project( still its working.) How it is possible?

Me
7 years ago
Reply to  Vishnudev K

Since we are using WebApplicationInitializer, the web.xml file is NOT required.

mohan
8 years ago

0
down vote

favorite

I want to create one functionality by implementing spring security.
In this I have one login page which contains username and password.
After user enter credentials user need to navigate to “Terms and
conditions” page. There will be two buttons. Accept and deny. If he
accept he can further go inside the application. If he clicks on Deny
he will be again come back to login page.

After user enter credentials user need to navigate to “Terms and
conditions” page. Here user should authenticated against ldap but
session should not get start. If user clicks on “Accept” button of
“Terms and conditions” page then only session should start.

I can not add much code here because it is confidential. However below things are there in configuration.

/*impactAuthenticationFilter is class which extends AbstractPreAuthenticatedProcessingFilter*/

/*successHandler is class which extends SavedRequestAwareAuthenticationSuccessHandler*/

mohan
8 years ago

I want to create one functionality by implementing spring security.
In this I have one login page which contains username and password.
After user enter credentials user need to navigate to “Terms and
conditions” page. There will be two buttons. Accept and deny. If he
accept he can further go inside the application. If he clicks on Deny
he will be again come back to login page.

After user enter credentials user need to navigate to “Terms and
conditions” page. Here user should authenticated against ldap but
session should not get start. If user clicks on “Accept” button of
“Terms and conditions” page then only session should start.

fredy hernan sanchez montaña
8 years ago

I just add the anotations and remove the xml and It did not take the *.config classes

mukesh tangri
8 years ago

I am getting “no such method exception” error when I try to start the server. I was able to get everything working with the xml based authentication but when ever I change it to Annotation based. Below is the full error. As defaultwessecurityhandler extends abstractsecurityexpressionhandler I verified the setapplicationcontext method exists in the jar. Any help to resolve the issue will be appreciated

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration’: Injection of autowired dependencies failed; nested exception is java.lang.NoSuchMethodError: org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler.setApplicationContext(Lorg/springframework/context/ApplicationContext;)V

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)

at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)

at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)

at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)

at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)

at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762)

at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)

at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)

at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)

at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)

at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)

at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4992)

at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492)

at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)

at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)

at java.util.concurrent.FutureTask.run(Unknown Source)

at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)

at java.lang.Thread.run(Unknown Source)

Caused by: java.lang.NoSuchMethodError: org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler.setApplicationContext(Lorg/springframework/context/ApplicationContext;)V

at org.springframework.security.config.annotation.web.builders.WebSecurity.setApplicationContext(WebSecurity.java:342)

at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:119)

at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:94)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1558)

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:399)

at org.springframework.security.config.annotation.configuration.AutowireBeanFactoryObjectPostProcessor.postProcess(AutowireBeanFactoryObjectPostProcessor.java:60)

at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.setFilterChainProxySecurityConfigurer(WebSecurityConfiguration.java:119)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

at java.lang.reflect.Method.invoke(Unknown Source)

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:642)

at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)

… 22 more

zeyi
5 years ago
Reply to  mukesh tangri

Excuse me,have you solved this problem?
I have a same one with you

Chris Linder
8 years ago

always getting this error WARNING: No mapping found for HTTP request with URI [/SecurityMVC/welcome] in DispatcherServlet with name ‘dispatcher’

user1234
8 years ago

great article,a little description of files like WebSecurityConfigurerAdapter or AbstractAnnotationConfigDispatcherServletInitializer would be more of a help to us.

j.j.marvin
8 years ago

Great sample!

It also can be moved to java 1.8 and latest spring:

1.8
4.1.5.RELEASE
4.0.0.RELEASE
1.2
3.0.1

Tried to jdk 1.8 and Tomcat 8.

Sam French
9 years ago

Your website is the best. Thanks!

? [c0d3r28] ?
9 years ago

This tutorial is now heavily out-dated

jcano
9 years ago

Changes to pom.xml to make it run. Thanks Myyong.

org.apache.maven.plugins

maven-eclipse-plugin

2.9

true

false

2.0

org.apache.maven.plugins

maven-war-plugin

false

Samuel Henrique
9 years ago

Can I enable both http basic and login form?

reddy
9 years ago

Thank YoU mkyong
🙂

lehoangdung
9 years ago

Thank you very much! Your article helps me a lot.

Ronald
9 years ago

Hi, If I go to the /admin1 it shows me the admin page, without the login, and the logout.
Should this not either ask me to login or deny me access?

Edgar de Graaff
9 years ago

Thanks, this really helped me getting started!

jef
9 years ago

Would really appreciate it if you also do a tutorial with jsf integration. Thanks!!

Zach
9 years ago

I love your tutorials by the way!

Is there a way to wire security using annotations like this in a preauthentication scenario or does preauthentication r still require xml configuration?