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.Table of Contents
Part 1: Introduction and Functional SpecsPart 2: Java classes
Part 3: XML configuration
Part 4: HTML Files
Part 5: Running the Application
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
- Run MySQL (install one if you don't have one yet)
- Create a new database:
spring_security_tutorial
- Import the following file which is included in the source code under the src/main/resources folder:
spring_security_tutorial.sql
Building with Maven
- Ensure Maven is installed
- Open a command window (Windows) or a terminal (Linux/Mac)
- Run the following command:
mvn tomcat:run
- 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
Note: If the project will not build due to missing repositories, please enable the repositories section in the pom.xml!
Access the Login page
- Follow the steps with Building with Maven
- Open a browser
- Enter the following URL (8080 is the default port for Tomcat):
http://localhost:8080/spring-security-tutorial/
- 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
- Ensure Maven is installed
- Open a command window (Windows) or a terminal (Linux/Mac)
- Run the following command:
mvn eclipse:eclipse -Dwtpversion=2.0
- 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
- 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 |
Share the joy:
|
Subscribe by reader Subscribe by email Share
thanks for all !
ReplyDeleteGreat! but I got error. How to fix? thanks a lot.
ReplyDelete[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>
@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:
ReplyDelete<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.
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?
ReplyDeletefigured out. never mind. thanks.
DeleteDo you have any user registration tutorial using Spring Security?
Authorization to db is working for me, but it is crazy slow. What did you do to resolve? thanks!
Deletethis 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.
ReplyDeleteAnyway, thanks so much for sharing your knowledge
@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).
ReplyDeleteYou are awesome.
ReplyDeleteThank you so much for tutorial... great tutorials.
ReplyDeleteI 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
Could you add new one after you delete it?
DeleteIn my case, the problem disappeared.
This comment has been removed by the author.
Delete@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.
ReplyDeleteThank you so much for your reply .
ReplyDeleteI 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
@Anonymous, remember the password needs to be hashed as MD5. Did you hashed the password first?
ReplyDeleteHi krams
ReplyDeletewhen 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)]
This was the most awesome spring tutorial I've ever seen.
ReplyDeleteThanks you very much Krams.
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.
ReplyDeleteIt is like the user has not logged out.
@Phil, I believe it's a configuration setting that you can declare in the spring-security.xml
ReplyDelete@krams, thanks for the reply. Inside the spring-security.xml you have specified <security:logout invalidate-session="true" .....
ReplyDeletebut 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.
@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
DeleteAs pointed out by Luke Taylor, "Please check the FAQ." (at http://static.springsource.org/spring-security/site/faq/faq.html#faq-cached-secure-page)
@krams, yes you are correct - many thanks. Apologies, I should have done some research before posting.
DeleteHi Krams,
ReplyDeleteGood 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
Hi Krams,
ReplyDeleteThank you ! Great tutorial !
Hi Krams,
ReplyDeleteThanks 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
/* Excuse me for my english */
ReplyDeleteFirst, 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
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.
ReplyDeleteThank you for your step by step explanation
very good tutorial!
ReplyDeleteThanks @krams. Nice tutorial. quick update.
ReplyDeleteRepo 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
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!
ReplyDeleteI just download this project but I am getting the following error. Am I missing anything here?
ReplyDeleteC:\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>
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.
DeleteYou 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.
Please see my post about the new issues and fix for this plugin http://krams915.blogspot.com/2012/08/copy-maven-plugin-updates.html
DeleteThanks for great tutorial.
ReplyDeleteIn this example, it show "public interface UserRepository extends JpaRepository"
ReplyDelete1) 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.
Super work.
ReplyDeleteI'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.
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.
ReplyDeleteThanks Krams, you are simply stunning. Great tutorial!!!
ReplyDeleteAmazing 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?
ReplyDeleteJust 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.
Deletewhat 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?
Deleteyour helo will be appreciated.
Thanks a lot....so nice explained step by step :)
ReplyDeleteGreat article... just what I was looking for...
ReplyDeleteThanks Mate
ReplyDeleteHello, 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:
ReplyDeleteapp.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.
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.
ReplyDeleteHi Krams, great tutorial. Sorry for my bad english.
ReplyDeleteIt 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.
Thanks so much Mark!
ReplyDeleteI 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!
Thanks great example but how to check if user already logged in?
ReplyDeleteI 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.
ReplyDeleteI have read your blog its very attractive and impressive. I like it your blog.
ReplyDeleteSpring 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