Integrating Spring Security with ExtJS Login Page

February 1, 2010 | By

spring security extjs login Integrating Spring Security with ExtJS Login Page

This tutorial will walk through how to configure ExtJS Login form (Ajax login form) instead of default Spring Security login.jsp.

Instead of using login.jsp from spring security, why do not use an ajax login form?

And How to integrate the ExtJS Login Form with Spring Security?

You did try to do it, the user is successfully authenticated, but the user is not redirected to the application main page. How to fix this situation? How to make it work?

It does not matter if you set the default-target-url in applicationContext-security.xml, or set a redirect URL on server side. It will not work this way.

The issue is that ExtJS make Ajax calls, and no redirect will work on server side. You have to redirect it on the client side, which is the ExtJS/javascript code.

First, you need to create the login form. You can use the javascript code provided by ExtJS and you can modify it to work with spring security.

If you take a look at the login.jsp, you will see three key points:

  1. URL / form action: j_spring_security_check
  2. Username input name: j_username
  3. Password input name: j_password

That is what you need to customize to make ExtJS Login form works! But do not be too comfortable, there are some issues you need to fix to make it work perfectly.

Take a look how login.js looks like (after customization):


	// Create a variable to hold our EXT Form Panel.

	// Assign various config options as seen.
	var login = new Ext.FormPanel({
		title:'Please Login',

		// Specific attributes for the text fields for username / password.
		// The "name" attribute defines the name of variables sent to the server.



		// All the magic happens after the user clicks the button

			formBind: true,
			// Function that fires when user clicks the button


				// Functions that fire (success or failure) when the server responds.
				// The server would actually respond with valid JSON,
				// something like: response.write "{ success: true}" or

				// response.write "{ success: false, errors: { reason: 'Login failed. Try again.' }}"
				// depending on the logic contained within your server script.
				// If a success occurs, the user is notified with an alert messagebox,

				// and when they click "OK", they are redirected to whatever page
				// you define as redirect.

				Ext.Msg.alert('Status', 'Login Successful!', function(btn, text){

					if (btn == 'ok'){
						window.location = 'main.action';


			// Failure function, see comment above re: success and failure.
			// You can see here, if login fails, it throws a messagebox
			// at the user telling him / her as much.

			failure:function(form, action){
				if(action.failureType == 'server'){
					obj = Ext.util.JSON.decode(action.response.responseText);

					Ext.Msg.alert('Login Failed!', obj.errors.reason);
					Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText);





If you make these changes and try to execute the application with a basic applicationContext-security.xml file, the user will be successfully authenticated, but is not going to be redirected.

What are we missing then?

You need to customize AuthenticationProcessingFilter class for spring security to perform actions on login.

The “onSuccessfulAuthentication” and “onUnsuccessfulAuthentication” methods need to return some JSON content. If user is successfully authenticated, then redirect to main page, otherwise, the application will show an error message.

This is MyAuthenticationProcessingFilter class:



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;


public class MyAuthenticationProcessingFilter extends AuthenticationProcessingFilter {

	protected void onSuccessfulAuthentication(HttpServletRequest request,
			HttpServletResponse response, Authentication authResult)
	throws IOException {
		super.onSuccessfulAuthentication(request, response, authResult);

		HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);

		Writer out = responseWrapper.getWriter();

		String targetUrl = determineTargetUrl( request );
		out.write("{success:true, targetUrl : \'" + targetUrl + "\'}");


	protected void onUnsuccessfulAuthentication( HttpServletRequest request,
			HttpServletResponse response, AuthenticationException failed )
	throws IOException {

		HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);

		Writer out = responseWrapper.getWriter();

		out.write("{ success: false, errors: { reason: 'Login failed. Try again.' }}");



And this is how applicationContext-security.xml looks like:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=""

	<security:global-method-security />

	<security:http auto-config="false" entry-point-ref="authenticationProcessingFilterEntryPoint">
		<security:intercept-url pattern="/index.jsp" filters="none" />
		<security:intercept-url pattern="/*.action" access="ROLE_USER" />

	<bean id="authenticationProcessingFilter" class="">
		<security:custom-filter position="AUTHENTICATION_PROCESSING_FILTER" />
		<property name="defaultTargetUrl" value="/main.html" />
		<property name="authenticationManager" ref="authenticationManager" />

	<security:authentication-manager alias="authenticationManager" />

	<bean id="authenticationProcessingFilterEntryPoint"
		<property name="loginFormUrl" value="/index.jsp" />
		<property name="forceHttps" value="false" />

    Usernames/Passwords are
    These passwords are from spring security app example
        <security:password-encoder hash="md5"/>
            <security:user name="rod" password="a564de63c2d0da68cf47586ee05984d7" authorities="ROLE_SUPERVISOR, ROLE_USER, ROLE_TELLER" />
            <security:user name="dianne" password="65d15fe9156f9c4bbffd98085992a44e" authorities="ROLE_USER,ROLE_TELLER" />
            <security:user name="scott" password="2b58af6dddbd072ed27ffc86725d7d3a" authorities="ROLE_USER" />
            <security:user name="peter" password="22b5c9accc6e1ba628cedc63a72d57f8" authorities="ROLE_USER" />

Now you can login using ExtJS login form.

I coded a sample application for this example. If you like it, you can download it from my GitHub:

Happy coding!

Filed in: ExtJS, Spring, Spring Security | Tags: , , , , ,

Comments (39)

Links to this Post

  1. 一些杂项资源 | 中文IT博客聚合 | January 15, 2011
  2. | May 5, 2011
  3. Integrating Spring Security with a JQuery Login Page? | September 14, 2011
  4. Confluence: tools and snippets | October 27, 2011
  5. JavaPins | January 8, 2012
  1. watazo

    a perfect mix, this tools (framework spring + extjs) is a interesting experience to work.
    thanks a good tutorial

  2. mascot

    Its :)
    Anyway how if I use username and password taken from database?

    Any solutions?

  3. Mayte

    Hi, I’ve got a situation, my security xml isn’t configured like yours ‘cuz has it was created in another project where the client side wasn’t ext js.
    Would you help me

  4. extjs beginner

    Nice tutorial and very helpful!

    I tried it and it works well, just have several questions though:
    1. My login page is login.html, my main page is main.html, how can I make it redirect to login.html even if I type “http://…/main.html” in browser? Now I still can access main.html without login.

    2. The username and password can be seen from firebug when click login button. Is there any way to make it safe and invisible?

    3. If I use my own ajax call to handle authentication, for example, use “url: ‘myAuthen.ajax’ instead of url:’j_spring_security_check’ in login.js file, does it make sense to use Spring security? How could I integrate that?

  5. Mayte

    Thanks for answer Loiane, but I’m already solve the problem. The thing is that I was using a preconfigured security module over spring, I adapted to my needs, but the thing was around you were talking at the beginning of your article, when the user logged in the system, redirection fails. But I put at the javascript in the success function part this:
    location.href = ‘home.htm'; //Main page request
    and problem solved
    Thanks very much
    PS: Your article was very useful to me. Thanks again

  6. yamina

    Muito obrigado, você viu como implementar a permissão para inserir, alterar, excluir?.
    Você tem algum exemplo sobre isso?

    Muito obrigado mais uma vez, Yamina

  7. Thanks, for your tutorial. it helps me alot to understand how to mix ajax and spring together.

  8. Mars

    Hi Loiane,

    I use Spring Security3.x with ExtJS, and I find that much changes from 2.x. Your code can’t be use driectly,
    do you have any idea?

  9. Joe

    Thanks for a great tutorial and source code.
    It was a great help on a project I’m working on.

  10. Mac

    where is this suppose to point to – j_spring_security_check ?

  11. tim

    moring Loiane,recently,I am writing a project with extjs and spring security ,what now i am facing to is if the user input a wrong username or password i was asked to give the user a due with chinese,what should i do?i found spring security provides some properties which is used to record the dues ,but i don’t know where spring securoty call them! any of your advices will help!thanks in advance!

  12. Thang Nguyen

    Hi Loiane,

    I am running this project but I got exception, Please help me fix it.

    WARNING: StandardWrapperValve[default]: PWC1406: Servlet.service() for servlet default threw exception
    at org.apache.catalina.connector.ResponseFacade.sendRedirect(
    at javax.servlet.http.HttpServletResponseWrapper.sendRedirect(
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(
    at org.apache.catalina.core.StandardWrapperValve.invoke(
    at org.apache.catalina.core.StandardContextValve.invoke(
    at org.apache.catalina.core.StandardPipeline.invoke(
    at com.sun.enterprise.web.WebPipeline.invoke(
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(
    at org.apache.catalina.core.StandardHostValve.invoke(
    at org.apache.catalina.connector.CoyoteAdapter.doService(
    at org.apache.catalina.connector.CoyoteAdapter.service(
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(
    at com.sun.grizzly.http.ProcessorTask.doProcess(
    at com.sun.grizzly.http.ProcessorTask.process(
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(
    at com.sun.grizzly.DefaultProtocolChain.execute(
    at com.sun.grizzly.DefaultProtocolChain.execute(
    at com.sun.grizzly.http.HttpProtocolChain.execute(
    at com.sun.grizzly.ProtocolChainContextTask.doCall(
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(
    at com.sun.grizzly.util.AbstractThreadPool$


    Thang Nguyen

  13. Jon

    Spent AGES trying to get this adapted to Spring Security 3. It seems as though a number of things have changed, namely:

    * applicationContext-security.xml *

    now looks something like:

    and * MyAuthenticationProcessingFilter * looks a bit like:

    public class MyAuthenticationProcessingFilter extends UsernamePasswordAuthenticationFilter {

    protected void successfulAuthentication(HttpServletRequest request,
    HttpServletResponse response, Authentication authResult)
    throws IOException, ServletException {

    //create a blank redirect strategy to prevent Spring automatically returning
    // page content in the output stream.
    SavedRequestAwareAuthenticationSuccessHandler srh = new SavedRequestAwareAuthenticationSuccessHandler();
    srh.setRedirectStrategy(new RedirectStrategy() {
    public void sendRedirect(HttpServletRequest httpservletrequest,
    HttpServletResponse httpservletresponse, String s) throws IOException {
    //do nothing, no redirect
    super.successfulAuthentication(request, response, authResult);

    HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
    Writer out = responseWrapper.getWriter();
    protected void unsuccessfulAuthentication(HttpServletRequest request,
    HttpServletResponse response, AuthenticationException failed)
    throws IOException, ServletException {

    HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
    Writer out = responseWrapper.getWriter();
    out.write(“{success: false, errors: ‘” + failed.getMessage() + “‘}”);


    Noting the implementation of the RedirectStrategy – otherwise Spring by default does a redirect, destroying your ‘success’ JSON response and causing a script error in IE. Seems to be ignored by Firefox, though.

  14. Jon

    Hmm, the applicationContext-security.xml was cut. Maybe this comment system doesn’t like XML…

  15. jeison

    Hi loiane,,,thanks for your goods tutorials,.

    Jon, Can you send me your applicationContenxt-security.xml

    I’m trying to implement this code with spring security 3.

  16. Brian


    I’d appreciate a copy of your applicationContext-security.xml changes for Spring Security 3 as well!

    If you can mail them to me at this address, I’d appreciate it!


  17. Loiane writte :

    “I coded a sample application for this example. If you like it, you can download it from my GitHub:

    Thanks Loiane for your great tuto !

  18. sguera

    ‘Spent AGES trying to get this adapted to Spring Security 3. It seems as though a number of things have changed, namely:

    * applicationContext-security.xml *

    now looks something like:’

    thanks Jon, u definitely saved my ass :D

  19. I love your writing style truly enjoying this site.

  20. I saw a lot of website but I conceive this one has something extra in it in it

  21. PPDL

    My 2 cents :)
    For spring-security 3.0.x, just use AuthenticationFailureHandler and AuthenticationSuccessHandler :)

  22. brmoez

    In the same context but with spring 3, I write:
    Your comment is awaiting moderation.

  23. Azhar


    I am facing a issue with your project (location :”).

    After i logout, the session should end rite!!
    but, it is not ending, i am able to access main.action page of your application.
    Please let me know about the solution. 
    thank you!!!!:)

  24. Tanvir Rahman

    Hi Loiane,

    I am new to extjs and springframework. after run this tutorial I got the following error…  Please help me to fix it up. Bellow I place the console output…. Please help me… I am waiting…

    8/05/2011 17:49:12 com.springsource.insight.tcserver.WeavingHelper findRepositoriesForClassPathINFO: file:/C:/springsource/tc-server-developer-2.1.1.RELEASE/spring-insight-instance/insight/collection-plugins/insight-collection-1.0.0.RELEASE.jar: aspects will be woven into the main Tomcat classloader8/05/2011 17:49:12 com.springsource.insight.tcserver.WeavingHelper findRepositoriesForClassPathINFO: file:/C:/springsource/tc-server-developer-2.1.1.RELEASE/spring-insight-instance/insight/collection-plugins/insight-plugin-jdbc-1.0.0.RELEASE.jar: aspects will be woven into the main Tomcat classloader8/05/2011 17:49:12 com.springsource.insight.tcserver.WeavingHelper findRepositoriesForClassPathINFO: file:/C:/springsource/tc-server-developer-2.1.1.RELEASE/spring-insight-instance/insight/collection-plugins/insight-plugin-tomcat-1.0.0.RELEASE.jar: aspects will be woven into the main Tomcat classloaderASPECTJ: aspectj.overweaving=true: overweaving switched ON8/05/2011 17:49:13 INFO: tc Runtime property decoder using memory-based key8/05/2011 17:49:13 INFO: tcServer Runtime property decoder has been initialized in 342 ms8/05/2011 17:49:14 com.springsource.tcserver.serviceability.rmi.JmxSocketListener initINFO: Started up JMX registry on in 185 ms8/05/2011 17:49:14 org.apache.coyote.http11.Http11Protocol initINFO: Initializing Coyote HTTP/1.1 on http-80808/05/2011 17:49:14 org.apache.catalina.startup.Catalina loadINFO: Initialization processed in 1392 ms8/05/2011 17:49:14 org.apache.catalina.core.StandardService startINFO: Starting service Catalina8/05/2011 17:49:14 org.apache.catalina.core.StandardEngine startINFO: Starting Servlet Engine: SpringSource tc Runtime 2.1.1.RELEASE/6.0.29.C.RELEASE8/05/2011 17:49:14 org.apache.catalina.startup.HostConfig deployDescriptorINFO: Deploying configuration descriptor CoreCPM.xml8/05/2011 17:49:15 org.apache.catalina.core.StandardContext listenerStartSEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListenerjava.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener at org.apache.catalina.loader.WebappClassLoader.loadClass( at org.apache.catalina.loader.WebappClassLoader.loadClass( at org.apache.catalina.core.StandardContext.listenerStart( at org.apache.catalina.core.StandardContext.start( at org.apache.catalina.core.ContainerBase.addChildInternal( at org.apache.catalina.core.ContainerBase.addChild( at org.apache.catalina.core.StandardHost.addChild( at org.apache.catalina.startup.HostConfig.deployDescriptor( at org.apache.catalina.startup.HostConfig.deployDescriptors( at org.apache.catalina.startup.HostConfig.deployApps( at org.apache.catalina.startup.HostConfig.start( at org.apache.catalina.startup.HostConfig.lifecycleEvent( at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent( at org.apache.catalina.core.ContainerBase.start( at org.apache.catalina.core.StandardHost.start( at org.apache.catalina.core.ContainerBase.start( at org.apache.catalina.core.StandardEngine.start( at org.apache.catalina.core.StandardService.start( at org.apache.catalina.core.StandardServer.start( at org.apache.catalina.startup.Catalina.start( at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke( at sun.reflect.DelegatingMethodAccessorImpl.invoke( at java.lang.reflect.Method.invoke( at org.apache.catalina.startup.Bootstrap.start( at org.apache.catalina.startup.Bootstrap.main( 17:49:15 org.apache.catalina.core.StandardContext listenerStartSEVERE: Skipped installing application listeners due to previous error(s)8/05/2011 17:49:15 org.apache.catalina.core.StandardContext startSEVERE: Error listenerStart8/05/2011 17:49:15 org.apache.catalina.core.StandardContext startSEVERE: Context [/CoreCPM] startup failed due to previous errors2011-05-08 17:49:23,975 WARN  [net.sf.ehcache.hibernate.AbstractEhcacheProvider][main] – A configurationResourceName was set to /META-INF/ehcache.xml but the resource could not be loaded from the classpath.Ehcache will configure itself using defaults.2011-05-08 17:49:24,374 WARN  [org.hibernate.cache.impl.bridge.EntityRegionAdapter][main] – read-only cache configured for mutable entity [com.springsource.insight.repo.metric.persist.PersistedMetric]2011-05-08 17:49:24,382 WARN  [org.hibernate.cache.impl.bridge.EntityRegionAdapter][main] – read-only cache configured for mutable entity [com.springsource.insight.repo.tag.persist.PersistedTag]2011-05-08 17:49:28,121 WARN  [][main] – Found more than one MBeanServer instance. Returning first from list.[TomcatWeavingInsightClassLoader@1142653] warning ignoring duplicate definition: jar:file:/C:/springsource/tc-server-developer-2.1.1.RELEASE/spring-insight-instance/insight/collection-plugins/insight-plugin-jdbc-1.0.0.RELEASE.jar!/META-INF/aop.xml[TomcatWeavingInsightClassLoader@1142653] warning ignoring duplicate definition: jar:file:/C:/springsource/tc-server-developer-2.1.1.RELEASE/spring-insight-instance/insight/collection-plugins/insight-collection-1.0.0.RELEASE.jar!/META-INF/aop.xml[TomcatWeavingInsightClassLoader@1142653] warning ignoring duplicate definition: jar:file:/C:/springsource/tc-server-developer-2.1.1.RELEASE/spring-insight-instance/insight/collection-plugins/insight-plugin-jdbc-1.0.0.RELEASE.jar!/META-INF/aop-ajc.xml[TomcatWeavingInsightClassLoader@1142653] warning ignoring duplicate definition: jar:file:/C:/springsource/tc-server-developer-2.1.1.RELEASE/spring-insight-instance/insight/collection-plugins/insight-plugin-tomcat-1.0.0.RELEASE.jar!/META-INF/aop-ajc.xml[TomcatWeavingInsightClassLoader@1142653] warning ignoring duplicate definition: jar:file:/C:/springsource/tc-server-developer-2.1.1.RELEASE/spring-insight-instance/insight/collection-plugins/insight-collection-1.0.0.RELEASE.jar!/META-INF/aop-ajc.xmlASPECTJ: aspectj.overweaving=true: overweaving switched ON

    • Loiane

      Hi Tanvir,
      It is missing a jar file on your classpath.
      Please get all the jar files from the sample project and it should work.

  25. Gurinder

    Please provide me some examples of EXT-JS with spring framework

    in advance

  26. reader22

    Thanks for the tutorials, i followed these.

    please provide a guide to use Extjs 3.2 with struts2. I tried to do a login like the above using struts2.But i’m stuck on forwarding the success to a jsp page. When i click login it goes to action class ,but it’s not redirecting to the other page. it will be helpful, if you can give a guide for struts2+Extjs

  27. anand

    thanks for tutorial can you please show us how we can do it in Grails and what will be the directory structure, i have tried it but it says on login request Failed to load source for: http://localhost:8080/j_spring_security_check.!topic/grails/HzyrRp726DMyou can take this for reference

  28. dasdasdas

    can you provide me example of ajax and spring security