Friday, March 15, 2013

How to create an Admin Section using Spring Security

I found that may be it is not clear to everyone how to add custom defined admin/user or in a nutshell defining custom roles to users and based on roles defining access privileges to users.
So here i will create a sample small App to assign roles programmatically as "admin" and "user". Based on the role i will redirect to their respective pages.


  1. One IDE for java development
  2. Maven ( just to build, don't worry if you don't have Maven installed you can build via any build tools)
  3. Spring version 3.2.1 
First for your better understanding I will add the project structure here:-

    WEB-INF structure...
    Now as you can see i have two folders named "admin" and "user" to differentiate admin section and normal user sections.
    I will start from explaining web.xml file.

    Here what I have done is I have added the three xml files that are necessary to run this app. Thats it.

    Now I will show you how I have mentioned which URL pattern is for Admins and which is for Normal users in the file named admin-spring-security.xml

    Here "adminSectionAuthProvider" is a bean class that implements Springs "AuthenticationProvider" interface. This bean will determine what roles to give to what user.

    Here "myHandler" is a bean that redirects the user according to the role.
    Other settings are self explanatory i guess. Otherwise you can read the springsource documentation for these or can google it.

    Now will show you the dispatcher servlet named admin-dispatcher-servlet.xml file. Its only used to add prefix and suffix to the pages for Spring MVC.

    For now there is nothing in my applicationcontextXML as i am using @Component for my beans. You can add your beans there.Still will add the skeleton FYR.

    Here is a simple entity class for our login. Its just a simple Pojo class which extends Springs UserDetails

    Now will show you the Authentication provider where I am taking the input from login page and validating the user.
    For now I am hardcoding username password. But you can implement your own way of authentication. Its just an example.

    Now I have to redirect the uesrs after validating. Here is the handler which does that programatically based on the role aded to the user.

    In my controller classes I just show some basic infos like username only. For example i will add logincontroller.

    The login.jsp is below

    The dependent jars are added via Maven Dependency. here is my pom.xml

    You can download the sources from here

    No comments:

    Post a Comment