Sunday, March 2, 2014

SpringMVC4 + Spring Data JPA + SpringSecurity configuration using JavaConfig

In this article we will see how to configure and integrate SpringMVC4, Spring Data JPA with Hibernate and SpringSecurity using JavaConfig.

1. First let's configure all the necessary dependencies in pom.xml


2. Configure database connection properties and email settings in application.properties


3. Configure common Service Layer beans such as PropertySourcesPlaceholderConfigurer and JavaMailSender etc in com.sivalabs.springapp.config.AppConfig.java


Observe that we have excluded the package "com.sivalabs.springapp.web.*" from component scanning using new REGEX excludeFilter type.
If we don't exclude web related packages and tries to run JUnit test for service layer beans we will encounter the following Exception:

java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling

Also note that we have enabled Caching using @EnableCaching, so we should declare CacheManager bean.

4. Configure Persistence Layer beans in com.sivalabs.springapp.config.PersistenceConfig.java as follows:



Here we have configured DataSource and JPA EntityManagerFactory bean using Hibernate implementation.
Also we have configured DataSourceInitializer bean to initialize and populate our tables with seed data. We can enable/disable executing this db.sql script by changing init-db property value in application.properties.
And finally we have enabled Spring Data JPA repositories scanning using @EnableJpaRepositories to scan "com.sivalabs.springapp.repositories" package for JPA repository interfaces.

5. Now let us configure Web related beans in com.sivalabs.springapp.web.config.WebMvcConfig.java


6. Configure DispatcherService using AbstractAnnotationConfigDispatcherServletInitializer convinient class.


Here few things to note are we configured AppConfig.class as RootConfig classes and WebMvcConfig.class as ServletConfigClasses which is similar to how we configure in web.xml using ContextLoaderListener and DispatcherServlet's contextConfigLocation .
Also we have registered OpenEntityManagerInViewFilter to enable lazy loading of JPA entity graphs in view rendering phase.

7. Let us configure SpringSecurity.

First let us create a SecurityUser class which extends our application specific User class and implements org.springframework.security.core.userdetails.UserDetails.


We will implement a custom UserDetailsService and use Spring Data JPA repositories to load User details.


Now create com.sivalabs.springapp.config.SecurityConfig.java which contains SpeingSecurity related bean definitions.


Update SpringWebAppInitializer which we created eariler to add SecurityConfig configuration class.


As per our SpringSecurity custom Form Login configuration, we will use the following login form in login.jsp.


Once we successfully login we can obtain the authenticated use details using and secure parts of the view using as follows:


You can find the source code at github https://github.com/sivaprasadreddy/sivalabs-blog-samples-code/tree/master/springmvc-datajpa-security-demo

There are few issues while running the same application on JBoss AS 7.1. I have made few changes to run on JBossAS7.1 and published code at https://github.com/sivaprasadreddy/sivalabs-blog-samples-code/tree/master/springmvc-datajpa-security-demo-jboss7

24 comments:

  1. Hi siva;
    this is a greate work, thinks a lot.

    just one thing : when accessing admin pages without ADMIN_ROLE we need to add Access Denied Page (i.e handling org.springframework.security.access.AccessDeniedException)

    ReplyDelete
  2. Hi siva ;
    very helpful tuto, greate work, thinks a lot.
    just one question : how to implement AccessDeniedHandler using JavaConfig ?

    ReplyDelete
    Replies
    1. Please see http://www.mkyong.com/spring-security/customize-http-403-access-denied-page-in-spring-security/

      Delete
  3. Hi siva:
    Thanks a lot, I've question about java config, Please clarify me.
    In my organization we are using JDK 6/JROCKIT and JBOSS 7.1.1 AS for develops the application,
    We are developing Spring MVC 3 application using old style xml configuration .
    Now i planned to migrate my Spring MVC 3 + Hibernate xml configuration application to pure java config application and i followed your tutorial series.
    Unfortunately My Spring MVC 3 + Hibernate pure java config application does not works on jboss 7.1 AS, But it works on both tomcat and jetty server
    With xml configuration working fine in jboss 7.1 AS. And I'm not tested the application with new WILDFLY 8 AS.Because we are using JDK 6/JROCKIT only.

    is there any problem in JBOSS 7 AS with SPRING MVC java config ?
    and
    should i upgrade JAVA version 6 to 7 and JBOSS 7 to WILDFLY 8 ?

    Please answer me.

    Thanks & Regards

    Kudpudeen

    ReplyDelete
    Replies
    1. What issues you are facing?

      Delete
    2. I'm getting 404 error page,

      please help me

      Delete
    3. Hi Siva

      I compiled this springmvc4-spring-data-jpa sample application in JDK 6 with small modification in its sources.
      Unfortunately i got 404 error while deploying this springmvc4-spring-data-jpa sample application on JBOSS 7.1.1 AS. no mapping found in JBOSS log.
      But it successfully deployed and executed in tomcat 7 server

      is there problem in JBOSS 7 AS with SPRING MVC java config ?

      Please help me.




      Delete
    4. Hi,
      I tried deploying on JBossAS71.1 and i am also facing issues.
      Still I couldn't figure out the root cause of the issue, but after few experiments I could deploy the app with few tweaks.
      Give me your email id, i will email you the code.

      Delete
    5. This comment has been removed by the author.

      Delete
  4. Hi Siva,
    Thank you for your solution.
    I would like to use it with Jboss and I have some error (as Kudpudeen .M) . if you can send me your jboss version I will be very happy.
    Thank you

    ReplyDelete
    Replies
    1. Hi,
      I have published code for JBoss AS 7.1 changes at https://github.com/sivaprasadreddy/sivalabs-blog-samples-code/tree/master/springmvc-datajpa-security-demo-jboss7.

      Delete
    2. Hi Siva,

      It's working well !!!!
      Sorry for the delay to answer ^^
      What did you change just to know what have you done ?

      Thank you again mate !

      Delete
  5. Hi there

    I'm currently facing an issue with Spring Data JPA and Spring Security. When i call the getOne method from my UserDetailsService implementation, it returns a null object, i've already setup the database connection using a jndi server resource.

    Is there an additional config for Spring Data JPA and Spring Security??

    ReplyDelete
    Replies
    1. Hi,
      Please try to check whether the Spring Data JPA methods are working fine or not first, just to figure out where is the root cause.

      Sometime back I also faced this kind of issue, spending a lot of time looking into Security configuration whereas the actual issue is with my Spring Data JPA Repository query.

      Delete
  6. Hello Sival,

    I want to understand why did you disable csrf() ?

    thanks

    ReplyDelete
  7. Hi Siva,
    I wanted to ask, once you have a userdetailsservice and wish to add a "Sign up new user" functionality, how do you add a new user to the repo?

    ReplyDelete
  8. Good work mate. Need your help here, I'm not able to login. I have created User table and did required entries. but it's not working. On debug I found that you don't have UserRepositary implementation class. How does that work.

    ReplyDelete
    Replies
    1. Hi,
      We don't need to implement Spring Data JPA interfaces, spring will do at runtime.
      What error you are getting?

      Delete
  9. Got that error and it was my mistake (in fact a very stupid one :), named USERS table as USER). This is sorted. But after I got over this, I got another issue where in it was looking for some authorities table. What was that? What is that used for. I just created a table with this name and did required entries but I'm not able to get the context here. Please guide me and yes many thanks for that prompt response.

    ReplyDelete
    Replies
    1. Hi,
      Please take a look at the Spring Security database shcema for managing users and roles. http://docs.spring.io/spring-security/site/docs/3.0.x/reference/appendix-schema.html

      Delete
  10. Hi,

    How to enable @EnableGlobalMethodSecurity. I imported your code and un commented @EnableGlobalMethodSecurity but I get error

    Caused by: java.lang.IllegalArgumentException: Expecting to only find a single bean for type interface org.springframework.security.authentication.AuthenticationManager, but found
    []

    ReplyDelete