Friday, January 13, 2012

Spring Security 3.1 - Implement UserDetailsService with Spring Data JPA (Part 5)

Review

We have just completed our application! In the previous sections, we have discussed the functional specs, created the Java classes, declared the configuration files, and wrote the HTMl files. In this section, we will build and run the application using Maven, and show how to import the project in Eclipse.


Running the Application

Access the source code

To download the source code, please visit the project's Github repository (click here)


Preparing the data source

  1. Run MySQL (install one if you don't have one yet)
  2. Create a new database:
    spring_security_tutorial
  3. Import the following file which is included in the source code under the src/main/resources folder:
    spring_security_tutorial.sql

Building with Maven

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn tomcat:run
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'tomcat'.
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from central
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from snapshots
    [INFO] ------------------------------------------
    [INFO] Building spring-security Maven Webapp
    [INFO]    task-segment: [tomcat:run]
    [INFO] ------------------------------------------
    [INFO] Preparing tomcat:run
    [INFO] [apt:process {execution: default}]
    [INFO] [resources:resources {execution: default-resources}]
    [INFO] [tomcat:run {execution: default-cli}]
    [INFO] Running war on http://localhost:8080/spring-security-tutorial
    Jan 14, 2012 11:52:54 PM org.apache.catalina.startup.Embedded start
    INFO: Starting tomcat server
    Jan 14, 2012 11:52:54 PM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
    Jan 14, 2012 11:52:54 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring root WebApplicationContext
    Jan 14, 2012 11:52:58 PM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Jan 14, 2012 11:52:58 PM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    
  5. Note: If the project will not build due to missing repositories, please enable the repositories section in the pom.xml!

Access the Login page

  1. Follow the steps with Building with Maven
  2. Open a browser
  3. Enter the following URL (8080 is the default port for Tomcat):
    http://localhost:8080/spring-security-tutorial/
  4. Currently there are two accounts included in the sample database. Here are the credentials:
    username password role
    john admin administrator
    jane user regular user

Import the project in Eclipse

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn eclipse:eclipse -Dwtpversion=2.0
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'eclipse'.
    [INFO] org.apache.maven.plugins: checking for updates from central
    [INFO] org.apache.maven.plugins: checking for updates from snapshots
    [INFO] org.codehaus.mojo: checking for updates from central
    [INFO] org.codehaus.mojo: checking for updates from snapshots
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from central
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from snapshots
    [INFO] -----------------------------------------
    [INFO] Building spring-security Maven Webapp
    [INFO]    task-segment: [eclipse:eclipse]
    [INFO] -----------------------------------------
    [INFO] Preparing eclipse:eclipse
    [INFO] [apt:process {execution: default}]
    [INFO] [eclipse:eclipse {execution: default-cli}]
    [INFO] Adding support for WTP version 2.0.
    [INFO] -----------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] -----------------------------------------
    
    This command will add the following files to your project:
    .classpath
    .project
    .settings
    target
    You may have to enable "show hidden files" in your file explorer to view them
  5. Open Eclipse and import the project

Conclusion

That's it! We've have successfully completed our Spring Security 3.1 tutorial. We've learned how to secure a Spring MVC application with Spring Security and integrate with a custom user database schema. Furthermore, we have simplified data access with the help of Spring Data JPA.

I hope you've enjoyed this tutorial. Don't forget to check my other tutorials at the Tutorials section.

Revision History


Revision Date Description
1 Jan 13 2012 Uploaded tutorial and Github repository
2 Jan 14 2012 Added revision history
3 Jan 15 2012 Added sample Maven output
4 Jan 19 2012 Added dependencies section
5 Jan 20 2012 Rephrased the logic behind CustomUserDetailsService, Rephrased Part 2
6 Jan 21 2012 Fixed Evgeny Goldin repository location

StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring Security 3.1 - Implement UserDetailsService with Spring Data JPA (Part 5) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

56 comments:

  1. Great! but I got error. How to fix? thanks a lot.

    [ERROR] Plugin com.goldin.plugins:maven-copy-plugin:0.2.3 or one of its dependen
    cies could not be resolved: Failed to read artifact descriptor for com.goldin.pl
    ugins:maven-copy-plugin:jar:0.2.3: Failure to find com.goldin.plugins:maven-copy
    -plugin:pom:0.2.3 in http://repo.maven.apache.org/maven2 was cached in the local
    repository, resolution will not be reattempted until the update interval of cen
    tral has elapsed or updates are forced -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
    ch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please rea
    d the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResoluti
    onException
    C:\2012dev\download\krams915-spring-security-tutorial-2c17470\krams915-spring-se
    curity-tutorial-2c17470\spring-security-tutorial>

    ReplyDelete
  2. @Anonymous, thank you for bringing this up. I have incorrectly placed the Evgeny Goldin Repository under the <repositories> section. It should be placed under the <pluginRepositories> section instead:

    <pluginRepositories>
         <pluginRepository>
              <id>evgeny-goldin.org</id>
              <name>Evgeny Goldin Repository</name>
              <url>http://evgeny-goldin.org/artifactory/repo/</url>
         </pluginRepository>
    </pluginRepositories>

    I have updated the pom.xml. Please pull the project again.

    ReplyDelete
  3. thank you Krams. Now I can build the project and can see the login page but I always fail to login using john/admin and jane/user."connections could not be acquired from the underlying database. besides this issue, it is very slow, it takes more than 30 seconds to show login failed. any ideas?

    ReplyDelete
    Replies
    1. figured out. never mind. thanks.

      Do you have any user registration tutorial using Spring Security?

      Delete
    2. Authorization to db is working for me, but it is crazy slow. What did you do to resolve? thanks!

      Delete
  4. this is a great tutorial, but I would remove the jpa data dependencies. At this level it is just very confusing and not being able to build in spring tool suite is a major problem, imo.

    Anyway, thanks so much for sharing your knowledge

    ReplyDelete
  5. @be, thanks for the feedback. I can't remove the Spring Data JPA dependencies. If I do, then it would be a different tutorial. If you don't want that dependency, I have a similar guide that doesn't use Spring Data JPA. You can find it in the tutorials section. Anyway, you should not worry about the dependencies since Maven should automatically retrieve them for you (unless you're referring to that STS version where Maven is somewhat compromised).

    ReplyDelete
  6. Thank you so much for tutorial... great tutorials.
    I was trying to run the project but there is error in POM.XML for execution plugins
    I am getting these errors:

    Plugin execution not covered by lifecycle configuration: com.mysema.maven:maven-apt-plugin:1.0:process (execution: default, phase: generate-sources)

    Plugin execution not covered by lifecycle configuration: com.goldin.plugins:maven-copy-plugin:0.2.3:copy (execution: create-archive, phase: compile)


    Could you please help
    Thank you

    ReplyDelete
    Replies
    1. Could you add new one after you delete it?
      In my case, the problem disappeared.

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

      Delete
  7. @hasan, can you try doing a Maven clean and then rebuilding the project? I have tested this project using the standalone Maven and also in Eclipse using m2Eclipse.

    ReplyDelete
  8. Thank you so much for your reply .
    I have one more question about running the application.
    I added some rows to the database to test from browser( home page ). Whenever I entered correct username and password it shows 'Login Failure' page. I think service class do not check the user information.
    Could you please help
    Thank you

    ReplyDelete
  9. @Anonymous, remember the password needs to be hashed as MD5. Did you hashed the password first?

    ReplyDelete
  10. Hi krams

    when i run this example i got the following exceptions please help me

    1) javax.persistence.PersistenceException: [PersistenceUnit: hibernatePersistenceUnit] Unable to build EntityManagerFactory


    2) org.hibernate.MappingException: Could not determine type for: com.manam.domain.Role, at table: user, for columns: [org.hibernate.mapping.Column(role)]

    ReplyDelete
  11. This was the most awesome spring tutorial I've ever seen.
    Thanks you very much Krams.

    ReplyDelete
  12. Great tutorial but after I have logged out, I can still access the previous user's pages by hitting the back key on the browser.
    It is like the user has not logged out.

    ReplyDelete
  13. @Phil, I believe it's a configuration setting that you can declare in the spring-security.xml

    ReplyDelete
  14. @krams, thanks for the reply. Inside the spring-security.xml you have specified <security:logout invalidate-session="true" .....
    but your example still seems to keep hold of the session as I can hit the back key after I have logged off.
    I am running your example code and have not made any changes.

    ReplyDelete
    Replies
    1. @Phil, I'm sure I've read this question previously. I believe the scenario is similar to the following http://forum.springsource.org/showthread.php?107711-Spring-Security-Logout-Back-Button-Page-History

      As pointed out by Luke Taylor, "Please check the FAQ." (at http://static.springsource.org/spring-security/site/faq/faq.html#faq-cached-secure-page)

      Delete
    2. @krams, yes you are correct - many thanks. Apologies, I should have done some research before posting.

      Delete
  15. Hi Krams,

    Good tutorial. I am following the LDAP tutorials of yours they are really good.I am trying to implement spring security with LDAP Authentication and Database authorization. Do you have any details regarding it. I am really looking for the security.xml how it looks like for both the configurations.

    Thanks

    ReplyDelete
  16. Hi Krams,
    Thank you ! Great tutorial !

    ReplyDelete
  17. Hi Krams,

    Thanks again for great Tutorial. Can you please let me know how to implement UserDetailsService to retrieve information from LDAP. I am using LDAP for authorisation and authencation.

    - Shirish

    ReplyDelete
  18. /* Excuse me for my english */
    First, I thank Mr. Krams for this very interesting tutorial. and i wonder if
    someone can help me by posting an updated pom.xml for this project, in fact there is some problems in the "goldin" dependency.
    thank you

    Note: the problem remains even if we change the pom.xml as it indicated in a comment above

    ReplyDelete
  19. I was searching for a good tutorial on spring security and came across this. I have tried out the steps given by you and I was able to understand the concept so much better.

    Thank you for your step by step explanation

    ReplyDelete
  20. very good tutorial!

    ReplyDelete
  21. Thanks @krams. Nice tutorial. quick update.

    Repo issue:
    Unfortunate how the great concept of maven keeping the dependencies and versions so years later (or actually if you are lucky days later) your code will just build.
    The repo moved, make the following update to pom.xml

    <!-- Repo for maven-copy-plugin-->
    <pluginRepository>
    <id>evgenyg.artifactoryonline.com</id>
    <name>Evgeny Artifactoryonline Repository</name>
    <url>http://evgenyg.artifactoryonline.com/evgenyg/repo/</url>
    </pluginRepository>

    Just noticed, @Jerry seems to have noticed this as well, different path but assume both work.

    for those new to JPA / spring, if you already have a MySQL db and the user root has a password then update the spring.properties file in src/main/webapp/WEB-INF

    ReplyDelete
  22. Thanks for the great tutorial. I was able to slip this in to a portal project I'm working on. Really loving the JPA integration. Thanks!

    ReplyDelete
  23. I just download this project but I am getting the following error. Am I missing anything here?

    C:\krams915-spring-security-tutorial-ff27843\spring-security-tutorial>mvn tomcat:run
    [INFO] Scanning for projects...
    [WARNING] The POM for com.goldin.plugins:maven-copy-plugin:jar:0.2.3 is missing, no dependency infor
    mation available
    [WARNING] Failed to retrieve plugin descriptor for com.goldin.plugins:maven-copy-plugin:0.2.3: Plugi
    n com.goldin.plugins:maven-copy-plugin:0.2.3 or one of its dependencies could not be resolved: Faile
    d to read artifact descriptor for com.goldin.plugins:maven-copy-plugin:jar:0.2.3
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building spring-security Maven Webapp 0.0.1-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [WARNING] The POM for com.goldin.plugins:maven-copy-plugin:jar:0.2.3 is missing, no dependency infor
    mation available
    [WARNING] Failed to retrieve plugin descriptor for com.goldin.plugins:maven-copy-plugin:0.2.3: Plugi
    n com.goldin.plugins:maven-copy-plugin:0.2.3 or one of its dependencies could not be resolved: Faile
    d to read artifact descriptor for com.goldin.plugins:maven-copy-plugin:jar:0.2.3
    [WARNING] The POM for com.goldin.plugins:maven-copy-plugin:jar:0.2.3 is missing, no dependency infor
    mation available
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 0.639s
    [INFO] Finished at: Tue Jul 31 22:55:31 EDT 2012
    [INFO] Final Memory: 4M/15M
    [INFO] ------------------------------------------------------------------------
    [ERROR] Plugin com.goldin.plugins:maven-copy-plugin:0.2.3 or one of its dependencies could not be re
    solved: Failed to read artifact descriptor for com.goldin.plugins:maven-copy-plugin:jar:0.2.3: Failu
    re to find com.goldin.plugins:maven-copy-plugin:pom:0.2.3 in http://evgeny-goldin.org/artifactory/re
    po/ was cached in the local repository, resolution will not be reattempted until the update interval
    of evgeny-goldin.org has elapsed or updates are forced -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following arti
    cles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResolutionException
    C:\krams915-spring-security-tutorial-ff27843\spring-security-tutorial>

    ReplyDelete
    Replies
    1. Anonymous, I actually received a couple of complaints regarding this plugin. I thought it was just a Maven issue, but it turns out the author has changed the plugin totally.

      You have to switch the old one to this new plugin:

      <groupId>com.github.goldin</groupId>
      <artifactId>copy-maven-plugin</artifactId>
      <version>0.2.5</version>

      See http://evgeny-goldin.com/wiki/Copy-maven-plugin for reference.

      Delete
    2. Please see my post about the new issues and fix for this plugin http://krams915.blogspot.com/2012/08/copy-maven-plugin-updates.html

      Delete
  24. In this example, it show "public interface UserRepository extends JpaRepository"
    1) Can we use hibernet instead of JPA and use our own User & role tables.(or build in spring framework)
    2) i could nt find the user and role tables in *.xml (mapping) file. is it build in spring framework.

    ReplyDelete
  25. Super work.
    I'm not able to get your tutorial works in eclipse. Do you have a post or everything else that would help me? I'm used to use Ant.

    ReplyDelete
  26. All your tutorials are really great! Do you have one where you manage data validation? Maybe I didn't see it. It's a really important point. Thank you.

    ReplyDelete
  27. Thanks Krams, you are simply stunning. Great tutorial!!!

    ReplyDelete
  28. Amazing guide man. I'm just wondering about this, how about if I want a welcome page with a link to a login page, which is normal in all sites?

    ReplyDelete
    Replies
    1. Just create a new welcome page and define that in the security.xml with permitAll attribute. It's like a login but without the actual login form and instead a URL.

      Delete
    2. what else i have to change to show a welcome page at the beginning? i defined the new welcome page in security but till login page loads at the beginning. should i do something in the controller or anywhere else?

      your helo will be appreciated.

      Delete
  29. Thanks a lot....so nice explained step by step :)

    ReplyDelete
  30. Great article... just what I was looking for...

    ReplyDelete
  31. Hello, thank you for the effort. The source code is really helpful but I have a problem. The package does not include a "deployProperties.properties" file which is referenced in spring-data.xml. I said, no big deal, created the file and entered the database properties as:
    app.jdbc.driverClassName=com.mysql.jdbc.Driver
    app.jdbc.url=jdbc:mysql://localhost:3306/springsecurity
    app.jdbc.username=root
    app.jdbc.password=
    I don't have a password for root. Also, I created a database named "spring_security_tutorial" but somehow I cannot use it. Anyway, I created another database named "springsecurity", therefore the jdbc url has that database's name. In case it depends on that, I also changed the name of the spring_security_tutorial.sql to springsecurity.sql.

    When running "mvn tomcat:run", I got the exception:
    INFO: Initializing Spring root WebApplicationContext
    [ERROR] [main 10:26:54] (SchemaUpdate.java:execute:175) could not get database metadata
    java.sql.SQLException: Connections could not be acquired from the underlying database!
    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106)
    ..........

    I also tried with a user configuration:
    app.jdbc.driverClassName=com.mysql.jdbc.Driver
    app.jdbc.url=jdbc:mysql://localhost:3306/springsecurity
    app.jdbc.username=erdinc
    app.jdbc.password=qwe123

    I got the same exception. I checked and saw that no table is created.

    Besides these, there is only one more change. The pom.xml included a plugin named maven-resources-plugin.

    This plugin's "executions" element was giving an error just like the one asked here "http://stackoverflow.com/questions/6352208/how-to-solve-plugin-execution-not-covered-by-lifecycle-configuration-for-sprin". I changed the pom.xml accordingly as:

    org.eclipse.m2e
    lifecycle-mapping
    1.0.0





    com.mysema.maven
    maven-apt-plugin
    ${maven.apt.plugin.version}

    process

    target/generated-sources/java
    com.mysema.query.apt.jpa.JPAAnnotationProcessor










    There was not a build error but "mvn tomcat:run" command gave the following warning:

    The POM for org.eclipse.m2e:lifecycle-mapping:jar:1.0.0 is missing, no dependency information available

    Maybe the reason is this one.

    All in all, what should I do next to make the code working. Also, I really didn't understand how "spring_security_tutorial.sql" is instructed to be run. I guess it is automatic.

    Thank you again.

    ReplyDelete
  32. Hello, it's me again. The above post can be deleted. I missed spring.properties in applicationContext.xml. Now, it is working. Sorry if I took your time.

    ReplyDelete
  33. Hi Krams, great tutorial. Sorry for my bad english.
    It helps me a lot but how it works, if i use Spring MVC to get the password from user and save it via controller in database.
    I look for examples but the most of them use hardcoded hashed passwords.
    I think, i must use something to make a md5 hash from password and save it via CrudRepository in database but i´m not sure.

    ReplyDelete
  34. Thanks so much Mark!

    I had some problems with , it only was working with textplain, but I changed the online hash generator, for tests, and it was working fine!

    Again Thanks!

    ReplyDelete
  35. Thanks great example but how to check if user already logged in?

    ReplyDelete
  36. I need concurrency control(max-seesions=1 per user) and logged in users list(by SessionRegistryImpl) in this application.You have given these features in another application but i need these features in this application.Please respond quickly.

    ReplyDelete
  37. I have read your blog its very attractive and impressive. I like it your blog.

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

    spring training in chennai spring hibernate training in chennai

    ReplyDelete
  38. I have read your blog its very attractive and impressive. I like it your blog.

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

    spring training in chennai spring hibernate training in chennai

    ReplyDelete