Saturday, August 23, 2008

Spring Security - Using custom Authentication Processing Filter

Recently I got a chance working with Spring security, formerly known as Acegi Security for spring. While working with the framework, I heard comments from friends and colleagues saying that spring security lacks proper documentation. So thought of sharing a little knowledge. By the way, this is first ever blog posting and kindly excuse me and let me know any errors and improvements.

Spring security offers a simple configuration based security for your web applications helping you secure your web application with out littering your business logic with any security code. It provides securing URL's based on the Role (Authorities), securing your business methods based on the ACL's.

The first step in hooking up the spring security to your web application is by specifying the DelegatingFilterProxy in your web.xml.

  1. <!--Spring security filter-->

  2. <filter>

  3. <filter-name>springSecurityFilterChain</filter-name>

  4. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>

  5. </filter

  6. <filter-mapping>

  7. <filter-name>springSecurityFilterChain</filter-name>

  8. <url-pattern>/*</url-pattern>

  9. <dispatcher>REQUEST</dispatcher>

  10. <dispatcher>INCLUDE</dispatcher>

  11. <dispatcher>FORWARD</dispatcher>

  12. </filter-mapping>

  13. <!--End spring security filter-->

If you want to externalize all of your security related configuration into a separate file, you can do so and add that to your context location param.
  1. <context-param>

  2. <param-name>contextConfigLocation</param-name>

  3. <param-value>

  4. /WEB-INF/beans.xml , /WEB-INF/springSecurity.xml </param-value>

  5. </context-param>

Now comes the part of security configuration for your application, Adding the URL security patterns is pretty simple and straight forward. Add all the URL patterns which you want to secure and add the wild card pattern at the end. You need to have some default principal and role even for non logged in users as you need to give access to pages like log in, register and forgot password kind of functionality even to non logged in users.

I tried to add comments to pretty much every element which I am using here.
As an example I added just a wild card intercept url which make every page of my application secure. You need to exclude different urls based on the roles.

  1. <security:http entry-point-ref="myAuthenticationEntryPoint" session-fixation-protection="newSession" >

  2. <!--add any of your cusotom url patterns to protect-->
  3. <security:intercept-url pattern="/login/**" access="ROLE_ANONYMOUS"/>
  4. <security:intercept-url pattern="/register/**" access="ROLE_ANONYMOUS"/>

  5. <security:intercept-url pattern="/**" access="ROLE_USER"/>

  6. <security:logout logout-success-url="/home.htm"/>

  7. <security:anonymous username="guest" granted-authority="ROLE_ANONYMOUS"/>

  8. </security:http>

  9. <!--name of my authenticationManager is authenticationManager-->

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

  11. <!--Cutom login filter which replaces the default AUTHENTICATION_PROCESSING_FILTER -->

  12. <bean id="customizedFormLoginFilter" class="" >

  13. <security:custom-filter position="AUTHENTICATION_PROCESSING_FILTER"/><!--replace the default one-->

  14. <property name="defaultTargetUrl" value="/main.htm"/><!--After a successful login, the user will be taken to this page-->

  15. <property name="authenticationFailureUrl" value="/home.htm?error=true" /><!--Authentication failed? take him to error page-->

  16. <property name="authenticationManager" ref="myAuthenticationManager"/> <!--Here it is the custom authenticationManager, login magic goes here -->

  17. <property name="allowSessionCreation" value="true" /> <!--Allow the application to create sessions-->

  18. </bean>

  19. <!--My custom auth manager-->

  20. <bean id="myAuthenticationManager" class="" />

  21. <!-- Automatically receives AuthenticationEvent messages -->

  22. <bean id="loggerListener" class=""/>

  23. <!--My authuntication entry point, can be replaced easily if we are doing custom commence of invalid auths.-->

  24. <bean id="myAuthenticationEntryPoint"

  25. class="" >

  26. <property name="loginFormUrl" value="/home.htm"/>

  27. </bean>

Following is my custom implementation of AuthenticationEntryPoint, which currently is not doing any thing except leveraging the commence to its super class which is the spring implementation of AuthenticationProcessingFilterEntryPoint. I hooked it to add any custom logic.

  1. public class CustomAuthenticationEntryPoint extends AuthenticationProcessingFilterEntryPoint {

  2. private static final Log logger = LogFactory.getLog(CustomAuthenticationEntryPoint.class);

  3. @Override

  4. public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException {

  5. super.commence(request, response, authException);

  6. }

  7. }

This is my custom authentication manager which actually does the custom login of the user. It will throw an BadCredentialsException in case of invalid credentials or thorws a AuthenticationServiceException in case of a service error (Database error, SQL error or any other error).

  1. public class CustomAuthunticationManager implements AuthenticationManager {

  2. @Autowired

  3. UserManagerService userManagerService;

  4. public Authentication authenticate(Authentication authentication) throws AuthenticationException {

  5. if(StringUtils.isBlank((String) authentication.getPrincipal()) || StringUtils.isBlank((String) authentication.getCredentials())){

  6. throw new BadCredentialsException("Invalid username/password");

  7. }

  8. User user = null;

  9. GrantedAuthority[] grantedAuthorities = null;

  10. try{

  11. user = userManagerService.getUser((String) authentication.getPrincipal(), (String) authentication.getCredentials());

  12. }

  13. catch(InvalidCredentialsException ex){

  14. throw new BadCredentialsException(ex.getMessage());

  15. }

  16. catch(Exception e){

  17. throw new AuthenticationServiceException("Currently we are unable to process your request. Kindly try again later.");

  18. }

  19. if (user != null) {

  20. List<Role> roles = user.getAssociatedRoles();

  21. grantedAuthorities = new GrantedAuthority[roles.size()];

  22. for (int i = 0; i &lt; roles.size(); i++) {

  23. Role role = roles.get(i);

  24. GrantedAuthority authority = new GrantedAuthorityImpl(role.getRoleCode());

  25. grantedAuthorities[i] = authority;

  26. }

  27. }

  28. else{

  29. throw new BadCredentialsException("Invalid username/password");

  30. }

  31. return new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), grantedAuthorities);

  32. }

  33. }

At the client side (jsp), the simple configuration you need to do is post the request to"/j_spring_security_check" with parameters "j_username" and "j_password".

That's pretty much all you need to do for enabling spring security to your existing web application. I will try to explain about doing the method security using ACL's and configuring the view using spring security tags in another post.


Anonymous said...

Nice. Very helpful. Thanks for posting this!

Anonymous said...

Thanks for a great example of a custom authentication manager!

Anonymous said...

It's really helpful but I have an understanding problem. If I try to setup a solution like yours I will get the error that no authentication-provider is defined in my xml-file. Did you leave the part out? Because that would be interesting for me.

Teja said...

Nothing was missed. If you can give me the exact error you are facing, I will try to help you solve the problem

Taras Matyashovsky said...

Hello Teja,
Thanks for good article.
I'm trying to implement authentication without form login. I tried to implement my own EntryPoint, AuthenticationProvider, etc., but it is not working. Have You ever tried to implement something similar? Will be very grateful for any useful links or examples. Thanks once more.

Anonymous said...

I am getting error for UserManagerService and Role can you tell me the class implementation or it is a spring security class

Teja said...

UserManagerService is a custom service which will fetch the user and roles by username and password. Role is my cusom object which finally endedup being a GrantedAutority which is a spring impl.

rishabhchandra said... is also helpful in understanding the http security.

Anonymous said...

hello teja,

i try to implement my own custom authentication Manager based on your example code, but faceing this problem:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_authenticationManager': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No authentication providers were found in the application context

??? i have listed the authentication Manager the way you shown. Or is it a namespace problem and my bean-tag is not recognized by the security app? thanks for your help and time...

Anonymous said...

hi teja,

i am getting springcontextholder object null and authentication null. can you help me out!

Taras Petrytsyn said...

Hi Teja, I use your example but have loop redirect starting my application, have you any idea what the problem is?

Anonymous said...

Nice straightforward example and very helpful. Thanks!

Manoj Saxena said...

While I have been able to customize the JasperServer to use existing iBatis/Struts infrastructure and integrate authentication using existing app, there is one thorn.

How can I change the login page to accept another field? Say I want user to enter Domain in addition to username and password. And use the three to authenticate and eventually show reports. I have been able to write my custom Dao that validates jasper user from my DB, but how do I get new attribute - domain to reach my Dao, so that it can be used to authenticate the user?
While customizing the login page to accept additional fields is straightforward - you just need to modify login.jsp and make it your login page - making the new values reach \'some Java handler\' is an issue.

Appreciate inputs on this.

Login filter said...

Nicely covered all the details


Anonymous said...

Hi all,

I wonder what is the implementation for

I tried this example in my project using Spring security 3 and the server complains on during start up as the class cannot be found? Does anyone know what I am missing?


Raju Komaturi said...

Hi Teja,

This example is very nice.Could you please post rest of the implementaion calless also.Thanks in Advance.

Raju k

Raju Komaturi said...

I am very new to this kind of stuff.Please help to post all the classes you implemented.

Raju k

Anonymous said...

I tried this code but spring is complaining about list of providers.
Property 'providers' threw exception; nested exception is java.lang.IllegalArgumentException: A list of AuthenticationProviders is required

how can i fix this..tnx

shanthi said...

Hi Teja can we make the custom authentication to use user id and password instead of user name... we have that requirement in our applciation please help me

Edwin Dhondt said...


Is it possible to show an example using a pre-authentication scenario, where a user is already authenticated by another system (e.g. SiteMinder) and we only want to use Spring security to get the authentication details from the http request header ?


Anonymous said...

The problem with this post is the same problem with a lot of documentation and probably the issue your colleagues were referring to when they complained about the spring documentation. You don't explain how all these pieces work in unison to achieve the goal. In fact, you don't even explain what the specific goal of the code is. You just show us each individual piece and it's up to us to infer the rest. It's like looking at a picture with a magnifying glass. You can see each little piece clearly, but you can't see the big picture without lots of mental gymnastics. I appreciate the post and I'm not trying to be harsh. It's just hard and time consuming to properly relay complex information.

aperez said...
This comment has been removed by the author.
aperez said...
This comment has been removed by the author.
aperez said...

To solution the error:
java.lang.IllegalArgumentException: No authentication providers were found in the application context.

You should add the tag &ltcustom-authentication-provider&gt in the bean definition myAuthenticationManager.

Anonymous said...

Could your page be any slimmer?

99198782672 said...


Can somebody tell me how to use spring security for any OS(Linux/Windows)authentication? Please reply asap.


Innocent said...

Very very nice article on spring security.
I would be very grateful if you can provide Tag definitions as well.

like -

what do u mean by "access" attribute in above tab etc.

Else every thing is great

sandeep said...

very nice article. To read more on spring security, you can refer to these link
Spring Security 3 – Form Login and Logout Tutorial
Spring Security 3 – MVC integration Tutorial

Sandeep Kumar said...

To read in detail, browse this link Spring Security login example using database

Jonathan Bispo said...

How can I include another field for authentication, for example j_some_id?


Ankur said...

Hi Tejas,

Thanks for sharing this helpful example.
I am beginner in Spring Security.

Here my question is if we want to use different parameter than "j_username" and "j_password". How can we do that?

I need to implement security for Spring REST web service.
Please advise.

Ankur said...

Hi Tejas ,I am using cleartrust for pre authentication and is overriding getPreAuthenticatedCredentials method.If the headers are null as is the case for the first time then user is redirected to login page where he can enter the credentials. however the problem I have is it loops thru this method atleast 10 times before actually continuing with the chain.This actually slows down the performance.

Can you suggest what needs to be done to fix this.

David Smith said...

Interesting Article

Spring online training Spring online training Spring Hibernate online training Spring Hibernate online training

spring training in chennai spring hibernate training in chennai

sai said...

Nice tutorial. Thanks for sharing the valuable information. it’s really helpful. Who want to learn this blog most helpful. Keep sharing on updated tutorials…
python training institute in marathahalli
python training institute in btm
Python training course in Chennai

haripriya said...

Great thoughts you got there, believe I may possibly try just some of it throughout my daily life.
Data Science Interview questions and answers
Data Science Tutorial

rohini said...

Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too.
Best Devops Training in pune
Microsoft azure training in Bangalore
Power bi training in Chennai

jefrin said...

Very good to read thanks for sharing
salesforce training in chennai

karthick said...

You are doing a great job. I would like to appreciate your work for good accuracy

CCNA Training in chennai

Swashthika said...

Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.
moto g service center in chennai
motorola service center in velachery
motorola service center in t nagar

jvimala said...

Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.
Selenium Training in Chennai | Best Selenium Training in chennai
Devops Course Training in Chennai | Best Devops Training in Chennai

pavithra dass said...

Great post!
Thanks for sharing this list!
It helps me a lot finding a relevant blog in my niche!
Java Training in Chennai
Java Training in Coimbatore
Java Training in Bangalore

Manisha Sudha said...
This comment has been removed by the author.
Manisha Sudha said...

Awesome blog...thanks for sharing valuable articles.....
Struts Training in Chennai
Struts Training institutes in Chennai
Struts Training Chennai
struts Training in Anna Nagar
struts Training in T Nagar
Wordpress Training in Chennai
SAS Training in Chennai
Spring Training in Chennai
Photoshop Classes in Chennai
DOT NET Training in Chennai

sherya said...

Wonderful article with great piece of information. Thanks for sharing this with us. I'll take reference from your blog. Do share more such informative articles.
Automation Anywhere Training in Chennai
Automation Training in Chennai
Automation Training Institute in Chennai
R Training in Chennai
Data Science Training in Chennai
RPA Training in Chennai
Automation Anywhere Training in Adyar
Automation Anywhere Training in Tambaram
Automation Anywhere Training in Anna Nagar

Riya Raj said...

Great blog!!! The information was more useful for us... Thanks for sharing with us...
Python Training in Chennai
Python course in Chennai
Python Training
Best Python Training in Chennai
Python training in Thiruvanmiyur
Python Training in Velachery
Hadoop Training in Chennai
Software testing training in chennai
Python Training in Chennai
JAVA Training in Chennai

shivam said...

Flying Shift - Packers & Movers in Bhopal

diya shivanya said...

Thanks for posting keep updating it.
Ionic Training in Chennai
Ionic training course
German Classes in Chennai
TOEFL Coaching in Chennai
Informatica Training in Chennai
Spoken English Classes in Chennai
Ionic Training in Tambaram
Ionic Training in Adyar

Anbarasan14 said...

I have been reading all your blogs regularly..I admit, this is one of the best blogs I have read till date. Great going.. Waiting for the next...
Spoken English Classes in Chennai
Spoken English Class in Chennai
Spoken English in Chennai
IELTS Training in Chennai
IELTS Chennai
Best English Speaking Classes in Mumbai
Spoken English Classes in Mumbai
IELTS Mumbai
IELTS Coaching in Anna Nagar
Spoken English Class in T Nagar

Manthra said...

I want to thank for sharing this blog, really great and informative. Share more stuff like this.
Ethical Hacking course in Chennai
Ethical Hacking Training in Chennai
Hacking course
ccna course in Chennai
Salesforce Training in Chennai
Angular 7 Training in Chennai
Web Designing course in Chennai
Ethical Hacking course in Thiruvanmiyur
Ethical Hacking course in Porur
Ethical Hacking course in Adyar

subhashini said...

Admire this blog. Keep sharing more updates like this
Data Science Training in Chennai
Data Science Course in Chennai
Data Science Courses in Bangalore
Data science course in coimbatore
Data Science Certification in Chennai
Data Science Classes in Chennai
Data Science Training Institute in Chennai
Software Testing Training in Chennai

sasi said...

Great experience for me by reading this blog. Thank you for wonderful article.
Angularjs course in Chennai
Angularjs Training in Bangalore
angular training in bangalore
Angularjs Training in Chennai
Angularjs Training institute in Chennai
Angular 4 Training in Chennai
web design training in coimbatore
php training in madurai

The India said...

Delhi Agra Jaipur Tour by Bus
Delhi to Jaipur Same Day Tour
Delhi One Day Tour Package
Delhi Sightseeing One Day
Delhi Sightseeing Tour by Bus
Delhi Jaipur One Day Tour Package
Haridwar, Rishikesh Tours by Volvo

Anonymous said...

For Data Science training in bangalore, Visit:
Data Science training in Bangalore

Anonymous said...

Nice Post
For AWS training in Bangalore, Visit:
AWS training

Anonymous said...

Visit for the Best AI training in Bangalore:- Artificial Intelligence training in Bangalore

harish kalyan said...

This is an awesome post.Really very informative and creative contents.
Data Analytics Courses in Chennai
Big Data Analytics Courses
Xamarin Training Institutes in Chennai
Best Spoken English Class in Chennai
TOEFL Coaching Centres in Chennai
french classes
content writing training in chennai
spanish language in chennai
Data Analytics Courses in Velachery
Data Analytics Courses in T Nagar

for ict 99 said...

Great Article
Cyber Security Projects for CSE Students
Project Centers in Chennai

JavaScript Training in Chennai
JavaScript Training in Chennai

Adhuntt said...

Great blog thanks for sharing Analyze and take over the competition with ease with Adhuntt Media’s digital marketing tools and strategies. Let’s kick-start your brand right now at Adhuntt Media
seo service in chennai

Karuna said...

Nice blog thanks for sharing Is this a special day for you? Beautiful and fragrant flowers are sure to make it even more amazing of a day no doubt. This is why Karuna Nursery Gardens offers you the best rental plants in Chennai that too at drop dead prices.
corporate gardening service in chennai

Pixies said...

Excellent blog thanks for sharing It’s very important to have the best beauty parlour equipment to run a successful salon. Pixies Beauty Shop is the best place in Chennai to get high quality imported top brands at the best price.
beauty Shop in Chennai

Customer relationship management said...

Wow it is really wonderful and awesome thus it is veWow, it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot.

oracle dba training in bangalore

oracle dba courses in bangalore

oracle dba classes in bangalore

oracle dba training institute in bangalore

oracle dba course syllabus

best oracle dba training

oracle dba training centers

Customer relationship management said...

This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points. To appreciate this I like to share some useful information.

perl training institutes in bangalore

perl training in bangalore

best perl training institutes in bangalore

perl training course content

perl training interview questions

perl training & placement in bangalore

perl training center in bangalore

Customer relationship management said...

It is very good and useful for students and developer.Learned a lot of new things from your post Good creation,thanks for give a good information at sap crm.

mysql dba training in bangalore

mysql dba courses in bangalore

mysql dba classes in bangalore

mysql dba training institute in bangalore

mysql dba course syllabus

best mysql dba training

mysql dba training centers

Customer relationship management said...

I have to voice my passion for your kindness giving support to those people that should have guidance on this important matter.

pega training institutes in bangalore

pega training in bangalore

best pega training institutes in bangalore

pega training course content

pega training interview questions

pega training & placement in bangalore

pega training center in bangalore

Customer relationship management said...

Excellent post for the people who really need information for this technology.

sql server dba training in bangalore

sql server dba courses in bangalore

sql server dba classes in bangalore

sql server dba training institute in bangalore

sql server dba course syllabus

best sql server dba training

sql server dba course syllabus

best sql server dba training

sql server dba training centers

svrtechnologies said...

Really thanks for sharing such an informative stuff....

data science tutorial

Garrick Co Ida said...

Great Article
Data Mining Projects

Python Training in Chennai

Project Centers in Chennai

Python Training in Chennai

Reshma said...

Amazing Post. keep update more information.
German Classes in Chennai
German Classes in Bangalore
German Classes in Coimbatore
German Classes in Madurai
German Language Course in Hyderabad
German Language Course in Chennai
German language course in bangalore
German language course in coimbatore
Selenium Training in Bangalore
Software Testing Course in Bangalore

meritstep1 said...

I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously in their life, he/she can earn his living by doing blogging.thank you for thizs article. pega online training , best pega online training ,
top pega online training

Indpac said...

Very useful blog thanks for sharing IndPac India the German technology Packaging and sealing machines in India is the leading manufacturer and exporter of Packing Machines in India.

Aruna Ram said...

Great blog and i recently visit this post and i am very impressed. Thank you...
Oracle Training in Chennai
Oracle Certifications
Social Media Marketing Courses in Chennai
Tableau Training in Chennai
Primavera Training in Chennai
Unix Training in Chennai
Graphic Design Courses in Chennai
Pega Training in Chennai
Oracle DBA Training in Chennai
Power BI Training in Chennai
Oracle Training in Tambaram

dhishageetha said...

This Blog is really informative!! keep update more about this…
Aviation Courses in Bangalore
Air Hostess Training in Bangalore
Airport Management Courses in Bangalore
Ground Staff Training in Bangalore
Aviation Institute in Bangalore
Air Hostess Academy Bangalore
Airport Management in Bangalore

Unknown said...

python course in coimbatore
python training in coimbatore
java course in coimbatore
java training in coimbatore
android course in coimbatore
android training in coimbatore
php course in coimbatore
php training in coimbatore
digital marketing course in coimbatore
digital marketing training in coimbatore
software testing course in coimbatore
software testing training in coimbatore

Unknown said...

python course in coimbatore
java course in coimbatore
python training in coimbatore
java training in coimbatore
php course in coimbatore
php training in coimbatore
android course in coimbatore
android training in coimbatore
datascience course in coimbatore
datascience training in coimbatore
ethical hacking course in coimbatore
ethical hacking training in coimbatore
artificial intelligence course in coimbatore
artificial intelligence training in coimbatore
digital marketing course in coimbatore
digital marketing training in coimbatore
embedded system course in coimbatore
embeddedsystem training in coimbatore

Priyanka said...

Attend The Artificial Intelligence course From ExcelR. Practical Artificial Intelligence course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Artificial Intelligence course.
Artificial Intelligence Course

Janu said...

Your information about asp is really interesting and innovative. Also I want you to share latest updates about asp. Can you update it in your website? Thanks for sharing.

Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery

nisha said...

Nice Blog. thanks for sharing this article. every contentb of this article is explained very clearly and the concepts are very unique.

Data Science Training Course In Chennai | Data Science Training Course In Anna Nagar | Data Science Training Course In OMR | Data Science Training Course In Porur | Data Science Training Course In Tambaram | Data Science Training Course In Velachery

nisha said...

Nice Blog. thanks for sharing this Blog. keep updating every concept of this blog is very Neatly represented.

Data Science Training Course In Chennai | Data Science Training Course In Anna Nagar | Data Science Training Course In OMR | Data Science Training Course In Porur | Data Science Training Course In Tambaram | Data Science Training Course In Velachery

Priyanka said...

Attend The Artificial Intelligence course From ExcelR. Practical Artificial Intelligence course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Artificial Intelligence course.
Artificial Intelligence Course