Spring Security


Tools and Technologies used

1) Eclipse IDE Mars Release (4.5.0)

2) Java 8

3) Spring framework 3.2

4) Spring security 3.2

5) Tomcat 8


Step 1

Create a new maven project from eclipse

SpringSecurity_createProj1

SpringSecurity_createProj2

SpringSecurity_createProj3

SpringSecurity_CreateProject4

SpringSecurity_CreateProject5


Step 2

Add Tomcat server in your eclipse

SpringSecurity_CreateProject6

SpringSecurity_CreateProject7

Step 3

Add all the spring security and spring mvc dependencies into the pom file.

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>com.kb</groupId>
  5.   <artifactId>SpringSecurityHelloWorld</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>SpringSecurityHelloWorld Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.  
  11.   <properties>
  12.         <org.springframework.version>3.2.7.RELEASE</org.springframework.version>
  13.         <spring-security.version>3.2.7.RELEASE</spring-security.version>
  14.     </properties>
  15.   <dependencies>
  16.     <dependency>
  17.       <groupId>junit</groupId>
  18.       <artifactId>junit</artifactId>
  19.       <version>3.8.1</version>
  20.       <scope>test</scope>
  21.     </dependency>
  22.      <!-- Spring MVC depends on these modules spring-core, spring-beans, spring-context, spring-web -->
  23.         <dependency>
  24.             <groupId>org.springframework</groupId>
  25.             <artifactId>spring-webmvc</artifactId>
  26.             <version>${org.springframework.version}</version>
  27.         </dependency>
  28.          
  29.         <!-- Spring Security Dependencies -->
  30.         <dependency>
  31.             <groupId>org.springframework.security</groupId>
  32.             <artifactId>spring-security-core</artifactId>
  33.             <version>${spring-security.version}</version>
  34.          </dependency>
  35.          <dependency>
  36.             <groupId>org.springframework.security</groupId>
  37.             <artifactId>spring-security-web</artifactId>
  38.             <version>${spring-security.version}</version>
  39.           </dependency>
  40.           <dependency>
  41.             <groupId>org.springframework.security</groupId>
  42.             <artifactId>spring-security-config</artifactId>
  43.             <version>${spring-security.version}</version>
  44.           </dependency>
  45.   </dependencies>
  46.   <build>
  47.     <finalName>SpringSecurityHelloWorld</finalName>
  48.     <plugins>
  49.             <plugin>
  50.                 <groupId>org.apache.maven.plugins</groupId>
  51.                 <artifactId>maven-compiler-plugin</artifactId>
  52.                 <version>2.5.1</version>
  53.                 <configuration>
  54.                     <source>1.8</source>
  55.                     <target>1.8</target>
  56.                 </configuration>
  57.             </plugin>
  58.         </plugins>
  59.   </build>
  60. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.kb</groupId>
  <artifactId>SpringSecurityHelloWorld</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringSecurityHelloWorld Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>
        <org.springframework.version>3.2.7.RELEASE</org.springframework.version>
        <spring-security.version>3.2.7.RELEASE</spring-security.version>
    </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <!-- Spring MVC depends on these modules spring-core, spring-beans, spring-context, spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>
         
        <!-- Spring Security Dependencies -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring-security.version}</version>
         </dependency> 
         <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>
  </dependencies>
  <build>
    <finalName>SpringSecurityHelloWorld</finalName>
    <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
  </build>
</project>

Step 4

Modify web.xml file

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.     <display-name>Spring MVC Application</display-name>
  6.  
  7.     <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml,
  15.             /WEB-INF/spring-security.xml
  16.         </param-value>
  17.         </init-param>
  18.         <load-on-startup>1</load-on-startup>
  19.     </servlet>
  20.     <servlet-mapping>
  21.         <servlet-name>mvc-dispatcher</servlet-name>
  22.         <url-pattern>/</url-pattern>
  23.     </servlet-mapping>
  24.  
  25.     <listener>
  26.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  27.     </listener>
  28.  
  29.     <!-- Loads Spring Security configuration file -->
  30.     <context-param>
  31.         <param-name>contextConfigLocation</param-name>
  32.         <param-value>
  33.             /WEB-INF/spring-mvc.xml,
  34.             /WEB-INF/spring-security.xml
  35.         </param-value>
  36.     </context-param>
  37.  
  38.     <!-- Spring Security filter -->
  39.     <filter>
  40.         <filter-name>springSecurityFilterChain</filter-name>
  41.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  42.     </filter>
  43.  
  44.     <filter-mapping>
  45.         <filter-name>springSecurityFilterChain</filter-name>
  46.         <url-pattern>/*</url-pattern>
  47.     </filter-mapping>
  48.  
  49. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Spring MVC Application</display-name>

	<!-- Spring MVC dispatcher servlet -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			/WEB-INF/spring-mvc.xml,
			/WEB-INF/spring-security.xml
		</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Loads Spring Security configuration file -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring-mvc.xml,
			/WEB-INF/spring-security.xml
		</param-value>
	</context-param>

	<!-- Spring Security filter -->
	<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>

</web-app>

We all know that filters are defined in web.xml to perform something before the actual request is happening.

Similarly org.springframework.web.filter.DelegatingFilterProxy filter is used to pass request to Spring authentication mechanism before being processed.
This filter checks for the url pattern defined for it and passes all the requests matching that pattern to spring security mechanism.

In the above case, pattern is /*, so all the requests will be filtered by this filter and pass through spring security mechanism.

Step 5

Create Spring-mvc xml file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb.*" />
  14.     <mvc:annotation-driven />
  15.      
  16.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  17.         <property name="prefix" value="/WEB-INF/pages/" />
  18.         <property name="suffix" value=".jsp" />
  19.     </bean>
  20. </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
 
    <context:component-scan base-package="com.kb.*" />
    <mvc:annotation-driven />
     
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Step 6

Create Spring-security.xml

  1. <beans:beans xmlns="http://www.springframework.org/schema/security"
  2.   xmlns:beans="http://www.springframework.org/schema/beans"
  3.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.   xsi:schemaLocation="http://www.springframework.org/schema/beans
  5.          http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  6.          http://www.springframework.org/schema/security
  7.          http://www.springframework.org/schema/security/spring-security-3.2.xsd">
  8.            
  9.     <http auto-config='true'>
  10.       <intercept-url pattern="/secured/*" access="ROLE_USER" />
  11.     </http>
  12.        
  13.     <authentication-manager>
  14.       <authentication-provider>
  15.         <user-service>
  16.           <user name="kb" password="kb1234" authorities="ROLE_USER" />
  17.         </user-service>
  18.       </authentication-provider>
  19.     </authentication-manager>  
  20.            
  21. </beans:beans>
<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.2.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-3.2.xsd">
           
    <http auto-config='true'>
      <intercept-url pattern="/secured/*" access="ROLE_USER" />
    </http>
       
    <authentication-manager>
      <authentication-provider>
        <user-service>
          <user name="kb" password="kb1234" authorities="ROLE_USER" />
        </user-service>
      </authentication-provider>
    </authentication-manager>   
           
</beans:beans>

< intercept-url > tag defines the pattern to configure all the URLs which needs to be secured.
In our case, /secured/* means, all the URLS which has /secured at the beginning will be secured.
And access attribute defines the user’s role who can access these secured URLs.

auto-config=’true’ provides the Auto login form , BASIC Authentication and logout services. By default this attribute will be false.

authentication-manager – is used to manage the authentication of the request based on the Authentication provider.

authentication-provider – is used to define the authentication mechanism and it could be any one of these
jdbc-user-service
ldap-user-service
password-encoder
user-service

I have implemented using user-service mechanism with username and password provided in security file directly.
We can also use DB call with the query to authenticate the in user.
We can also use our own class/third party system to define authentication mechanism.

Step 7

Let’s create public hello world jsp page

  1. <html>
  2. <head>
  3.        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  4. <title>Insert title here</title>
  5. </head>
  6. <body>
  7.      <h3>Hello World!</h3>
  8.      <h4>${message}</h4>
  9. </body>
  10. </html>
<html>
<head>
       <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
     <h3>Hello World!</h3>
     <h4>${message}</h4>
</body>
</html>

Step 8

Let’s create secured hello world jsp page

  1. <html>
  2. <head>
  3.      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  4. <title>Insert title here</title>
  5. </head>
  6. <body>
  7.      <h3>Hello World!</h3>
  8.      <h4>${message}</h4>
  9. </body>
  10. </html>
<html>
<head>
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
     <h3>Hello World!</h3>
     <h4>${message}</h4>
</body>
</html>

Step 9

Build the project ->Right click on project and select maven-install

SpringSecurity_BuildProject

Step 10

Deployment of our application

Now go to the target folder of project and copy the war file SpringSecurityHelloWorld.war

E:\workspace\Spring-security-ws\SpringSecurityHelloWorld\target\SpringSecurityHelloWorld.war

Paste it in the tomcat’s webapps folder
E:\workspace\Spring-security-ws\SpringSecurityHelloWorld\target

Step 11

Start the server

Right click on server and click on start as shown below

SpringSecurity_ServerSrtart

Step 12

Open browser

Type http://localhost:8080/ and see whether server window opens
If not then double click on server in eclipse and keep server location as below

SpringSecurity_ServerWindow

Step 13

Access the below url

http://localhost:8080/SpringSecurityHelloWorld/public/pages

SpringSecurity_Output_welcomePage

Step 14

Now try to access secured url

http://localhost:8080/SpringSecurityHelloWorld/secured/pages

You should get default spring login form

SpringSecurity_DefaultForm

Notice here that secured page is not accessible directly, we need to provide valid credentials to access this page.
Spring has displayed its own login form, please enter valid user name and password and then access secured pages.

Step 15

Enter invalid credentials and see the output

SpringSecurity_Invalid_Credentials

Step 16

Enter valid credentials which are as below

Username – kb
Password – kb1234

SpringSecurity_valid_Credentials

Download this project SpringSecurityHelloWorld.zip
Share this article on

Comment (62)

  1. Hi

    First of all thanks for this post. I am new to spring security and trying to understand use of Authentication provider, I created project as per this post.

    I am trying to understand below portion from spring-security.xml file

    I understand that authentication happens on first request that comes in. After the user has
    been authenticated and tries to access another page, will CustomAuthenticationProvider call authenticate function all over again. If not, how does the application work until user signs out or timeout? If the information store somewhere in applications that the user has been authenticated and is used on request going back and forth

    Thanks in advance!

  2. @Component
    public class CustomAuthenticationProvider implements AuthenticationProvider{

    @Autowired
    private CustomUserService userService;

    }

    in this class always getting “userService” as null.
    Please help.

  3. I got below error

    No mapping found for HTTP request with URI [/SpringSecurityHelloWorldCustomLogin/login] in DispatcherServlet with name ‘mvc-dispatcher’

  4. Hello,

    I am doing something similar but my CustomAuthentcationProvider it not doing any lower level calls (call to DAO to check for the user), I am not sure why.

    I Autowired it still it doesn’t work.
    Can you help me with this.

  5. Hello. Thank you for a great tutorial! I’ve implemented this in my project and it mostly works. I’m using Postman to test and if I don’t provide any authentication header my custom auth class (CustomAuthenticationProvider) is never called and I am able to access my REST service.

    It seems as if Anonymous requests bypass this security. How can I prevent all Anonymous requests?

        1. Do you have an answer for my question?
          It seems as if Anonymous requests bypass this security. How can I prevent all Anonymous requests?

          1. Karibasappa G C (KB)

            < intercept-url pattern="/secured/*" access="ROLE_USER" / >

            This line should allow to access only for those users who have ROLE_USER, It should not allow for anonymous as they don’t have this role….Please let me know if its any specific case.

            1. What line? Was there supposed to be code in your last response?

              Here is how I have my Spring security xml setup now.

              I appreciate the help!

                1. It looks like the web site is stripping XML from the comment. I’ll try replacing the with %

                  The only way I was able to see yours was to view the source for the page.

                  %http auto-config=’true’%
                  %intercept-url pattern=”/services/**” access=”ROLE_USER” /%
                  %csrf disabled=”true”/%
                  %anonymous enabled=’false’/%
                  %/http%

                  1. I figured it out. My “context-root” wasn’t set right in jboss-web.xml

                    It was set to “/services”

                    When I change it to “/” everything works.

                    Thank you for the help!

  6. Hello. Good post.

    I would like to know if it is possible to perform several authentication methods with spring security. That is to say, the case of authenticating users through a form or that the same can be authenticated using another means for example with your gmail account through gmail. I know that with spring security there is the possibility of performing encrypted token authentication but I have not seen that it can be done both ways in the same application using spring security.

    1. Karibasappa G C (KB)

      Good question!!

      We can do that in spring security.

      For applications to authenticate users through third parties .The best option to use is OAUTH using tokens which is more secure and widely accepted one.

      Please check this article on the same.

      1. Thanks for your answer.

        I have read the article and it is very clear, excellent. To which also in another project that I was working with spring security I implemented using OAuth2.

        But I have not yet managed to perform an authentication integrating both: authentication using credentials user and password, or, when it is authentication using a third party login for example through facebook, but this within the same application. That is, in case of using the authentication of my app will be validated with the records of the DB but in case of the authentication through third party login, authenticate it in my app through a security token.

        Thank you again for your attention.

  7. Karibasappa,

    Great tutorial!

    I have a small doubt. In the code below, how can I catch the message given in the bad credentials exception in a Spring MVC controller where I call the custom authentication code.

    if (user == null || !user.getUsername().equalsIgnoreCase(username)) {
    throw new BadCredentialsException(“Username not found.”);
    }

    if (!password.equals(user.getPassword())) {
    throw new BadCredentialsException(“Wrong password.”);
    }

    Thanks.

    1. Karibasappa G C (KB)

      Hi Maneesh,

      Thank you!!

      You can catch the message of any Exception thrown by the Authentication provider in the controller using SPRING_SECURITY_LAST_EXCEPTION session attribute

      Its a session attribute set by spring security whenever any exception is thrown in the authentication provider.

      So in your controller, you can use the below code and get the exception message

      1. Object lastException  = request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
      2.  
      3. if (lastException  != null)
      4.         {
      5.            
      6. String exceptionMsg = ((Exception) lastException).getMessage();
      7. }
      Object lastException  = request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
      
      if (lastException  != null)
      		{
      			
      String exceptionMsg = ((Exception) lastException).getMessage();
      }

      You can add it in the model attribute to send it to JSP page.

  8. Hi,

    Interesting post. I have a question. You used AuthenticationProvider to wire-up your code which performs both authentication and authorization. Although this approach is simple to implement but your custom AuthenticationProvider should be doing authentication only and not both.

    1. Karibasappa G C (KB)

      Hi John,

      If you look at my authentication provider, I am not doing any authorization there, I have just taken the user roles and passing it to Spring security using UsernamePasswordAuthenticationToken as below

      1.   return new UsernamePasswordAuthenticationToken(user, password, authorities);
        return new UsernamePasswordAuthenticationToken(user, password, authorities);

      Authorization will be done by Spring using the Roles passed to this token.

      Thanks!!

  9. This is misleading information. on your security xml in above post, you didn’t mention tag but on your downloaded code, you had included it.

    Please avoid such mistakes.

    1. Karibasappa G C (KB)

      Can you tell me which tag you are talking about ?
      If you just say tag,i cant understand anything, if you tell me exact piece of code i can correct it after verifying the same.

      In download code there is a login form tag in security xml , if you are talking about that, then you are wrong, that is only for using custom login form which is an extra piece of code used for another article.

      Please tell me the details where you are finding discrepancy.

      Thank you!!

  10. Hi,

    I am trying to authenticate my JAX-RS rest APIs using spring authentication . I have created spring filter chain proxy referring this link here http://shazsterblog.blogspot.in/2014/07/spring-security-custom-filterchainproxy.html. I want to have basic authentication for my APIs. I don’t know where to specify basic authentication configuration. I have created CustomAuthenticationProvider and CustomUserDetailsService. When I hit any service URL it says 403 – Access Denied and when I hit /login the request return 200. How do I implement my login service and how to specify the session timeout. Please help me with this.

    1. Karibasappa G C (KB)

      Hi,

      If you want to store the credentials for basic authentication in xml you can put it in the xml file as explained in this post http://javainsimpleway.com/spring-security-hello-world-project/ or if you want to get it from DB then you can use this link http://javainsimpleway.com/spring-security-using-database-authentication/
      Then hit the service, it will prompt for authentication and then provide the same credentials.

      for session timeout after 15 minutes, you can put below config in web.xml

      1. <session -config>
      2.     < session-timeout>15< /session-timeout>
      3. < /session-config>
      4. </session>
      <session -config>
          < session-timeout>15< /session-timeout>
      < /session-config>
      </session>

      Thank you!!

  11. nice post,But i want to store roles(like admin,sec user,manage,corp user etc.) in database and based on login i want to fetch that roles from db and display to user in terms of menus

    1. Karibasappa G C (KB)

      Thanks Iliyas!!

      I am just trying to understand your requirement.

      When the user provides login credentials and click on login, you need to fetch all the roles of the logged in user and display it in the Menu.

      Please correct me If my understanding is incorrect,but assuming its correct, you need to get the roles from below API
      Collection< ? extends GrantedAuthority> authorities = (Collection< ? extends GrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
      and use it wherever you want.

      you can see below lines in HomeController.java in this article

      1. Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      2.         CustomUser user=null;
      3.         if (principal instanceof CustomUser) {
      4.         user = ((CustomUser)principal);
      5.         }
      6.      
      7.     String name = user.getUsername();
      8.     model.addAttribute("username", name);
      Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
              CustomUser user=null;
              if (principal instanceof CustomUser) {
              user = ((CustomUser)principal);
              }
           
          String name = user.getUsername();
          model.addAttribute("username", name);

      we are getting user name from principal and adding inside model attribute

      Similalry you can get the roles from principal and add them inside model attribute using

      1. model.addAttribute("authorities",principal.getAuthorities());
      model.addAttribute("authorities",principal.getAuthorities());

      and access them in JSP as below

      1. < c:forEach items="${authorities}" var="authority">
      2. ${authority.authority}
      3. < /c:forEach>
      < c:forEach items="${authorities}" var="authority">
      ${authority.authority}
      < /c:forEach>

      Thank you!!

      1. I have mail my example project to your mail id .Please go through it and tell me what i need to customize in my project to get roles from database.Thank you.

            1. Karibasappa G C (KB)

              I have checked your code.

              You have MainController in your project.

              So add below code in that controller

              1. model.addAttribute("authorities", SecurityContextHolder.getContext().getAuthentication().getPrincipal().getAuthorities());
              model.addAttribute("authorities", SecurityContextHolder.getContext().getAuthentication().getPrincipal().getAuthorities());

              and add below code in your jsp wherever you want to display ex hello.jsp

              1. < c:forEach items="${authorities}" var="authority">
              2. ${authority.authority}
              3. < /c:forEach>
              < c:forEach items="${authorities}" var="authority">
              ${authority.authority}
              < /c:forEach>
              1. At the time of login first username and password is validate then based on userid>> roles and privileges(roles are interms of comma seperated like AB,BC,CD etc in single column) of that user get selected ,and based on database roles values menu should be display .Only that menu items are enable which exists in database ,if not then that menu link should be disable.So how i can achieve this requirement.Hope i will get expected solution.Thank you.

                1. Karibasappa G C (KB)

                  In my above previous reply, you can find the solution of how to get the roles and display them in JSP.

                  You just need to put them in menu using html div and css code.

                  enable the menu using jquery if roles > 0 else disable it using jquery.

                    1. I want to use filter for intercept url as shown below.

                      how to customize “securityMetadataSource” to fetch roles from db.Thank you

    1. Karibasappa G C (KB)

      Completely agree with you, we should do that.

      I have just not focused on Exception modularity in this article but good point.

      Thanks!!

  12. Hi KB, I liked your post, i have similar integration with siteminder .. i need to read groupmembership header also part of my request for the roles . can you please share some details how to achieve it ?

    1. Karibasappa G C (KB)

      Hi Jidh,Thanks !!

      SiteMinder comes with the filter called “RequestHeaderAuthenticationFilter” which receives only “User”from the request header.

      To add anything else into the header and to get it read from the site minder filter,we have to write our own filter class which can extend the “RequestHeaderAuthenticationFilter”.

      Inside our own filter , write a logic which will read the group membership from the header.

      Inject this custom filter in the place where we inject existing filter.

  13. I was looking for looking for a tutorial on this for a very long time and this somehow hadn’t shown up anywhere. It’s just what I needed and helped me immensely. Thank you very much! 🙂

      1. Karibasappa G C (KB)

        Hi Jake , Thanks for reading it!!

        His issue was with web.xml where he missed importing some config files.

        Please send the error which you are facing along with web.xml and spring config files , will check it and let you know.

  14. thanks you very much for the answer , but it appears an error like this

    Severe: Exception while invoking class com.sun.enterprise.web.WebApplication start method
    java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.security.filterChains’: Cannot resolve reference to bean ‘org.springframework.security.web.DefaultSecurityFilterChain#0’ while setting bean property ‘sourceList’ with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.security.web.DefaultSecurityFilterChain#0’: Cannot resolve reference to bean ‘org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0’ while setting constructor argument with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0’: Cannot resolve reference to bean ‘org.springframework.security.authentication.ProviderManager#0’ while setting bean property ‘authenticationManager’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.security.authentication.ProviderManager#0’: Cannot resolve reference to bean ‘org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0’ while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0’: FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.security.authenticationManager’: Cannot resolve reference to bean ‘customAuthenticationProvider’ while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘customAuthenticationProvider’ is defined
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:138)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:130)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:269)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:301)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:461)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
    at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
    at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
    at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:745)

  15. Hi Agung,

    As per my observation, you have defined the bean customAuthenticationProvider twice,once using @Component annotation in the CustomAuthenticationProvider class and other one is inside spring security xml as below

    < beans:bean id="customAuthenticationProvider" class="id.co.iconpln.authentication.CustomAuthenticationProvider">

    always XML bean definition takes priority than annotation one which is the issue i think.

    Can you please remove the above bean declaration from the spring security config file.

    Let me know if that helps, if not send me complete stack trace.

  16. Hi Agung,

    Thanks for reading !!

    You are getting NULL pointer exception, there is a chance that the object which you are injecting could be NULL.

    Please check whether the below CustomUserService you are injecting is defined as spring bean

    @Autowired
    private CustomUserService userService;

    Can you post or email me your CustomUserService class and CustomAuthenticationProvider , i will have a look into it.

    1. thank you for replying , I really appreciate it , I ‘ll send an email, but I do not know your email , can you tell me your email

    2. thank you for replying , I really appreciate it

      this my class CustomAuthenticationProvider
      import ….
      @Component
      public class CustomAuthenticationProvider implements AuthenticationProvider {

      @Autowired
      private CustomUserService userService;

      public Authentication authenticate(Authentication authentication) throws AuthenticationException {

      String username = authentication.getName();
      String password = (String) authentication.getCredentials();

      CustomUser user = userService.loadUserByUsername(username);

      if (user == null || !user.getUsername().equalsIgnoreCase(username)){
      throw new BadCredentialsException(“Username not found.”);
      }

      if (!password.equals(user.getPassword())) {
      throw new BadCredentialsException(“Wrong password.”);
      }

      Collection authorities = user.getAuthorities();

      return new UsernamePasswordAuthenticationToken(user, password, authorities);
      }

      public boolean supports(Class arg0) {
      return true;
      }

      }

      and this my custom user service
      @Service
      public class CustomUserService implements UserDetailsService {

      @Autowired
      private UserDAOImpl userDao;

      public CustomUser loadUserByUsername(String username) throws UsernameNotFoundException {
      return userDao.loadUserByUsername(username);
      }
      }

      i already send my script and my sturcture in email

  17. thanks for your post,

    im trying implement but i have problem like this

    java.lang.NullPointerException
    at CustomAuthenticationProvider.authenticate(CustomAuthenticationProvider.java:32)

    CustomUser user = userService.loadUserByUsername(username); <– this line

    HTTP Status 500 –

    type Exception report

    message

    descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

    exception

    java.lang.NullPointerException

    note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1.2.2 logs.
    GlassFish Server Open Source Edition 3.1.2.2

    1. Since, I am using default login page provided by Spring,we can not achieve it as it is.

      But we can add any number of fields in the custom login page and achieve this.

      Please refer this post for the same ,there i have added only 2 fields , but yes we can add as many fields as we want. http://javainsimpleway.com/spring/spring-security-using-custom-login-form/

      But for this , we need to write custom authentication provider as explained in this post.

      I will try to write a new post for the same.

      Thanks for this.

Leave a Comment

  • You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" extra="">

    • Please answer this simple challenge to post your valuable comment *