Spring Security hello world example

In this post, we will see how to apply basic spring security to spring mvc hello world example.

Spring MVC tutorial:

If you want to secure your spring web application , you just need to configure some files to make it happen using spring security. We will apply login security on hello world example. So when only authorised users will be able to access hello world message.

Here are steps to apply basic spring security on spring mvc hello world example.

Step 1: 
Create Spring mvc hello world example named SpringSecurityHelloWorldExample . It will create basic spring mvc application.

Step 2: 
Add spring security to pom.xml. You need to add following dependencies to the pom.

pom.xml 
Step 3: 
Modify hello.jsp in /WEB-INF/ folder
Step 4:  

Now we need to add spring configuration xml. Create a file named spring-security.xml.
intercept-url configure for which pattern what kind of security is configured. For example: If http request url has pattern /hello*(hello.jsp,helloworld.html), it will be accessed to ROLE_ADMIN only.

We have hardcoded username(java2blog) and password(java123)   in authentication manager, so if user provides correct credential for admin then only he will be able to access helloworld.htm/.

We have not configured any login page here, so spring security will generate one for us.

Step 5: We need to change in web.xml to configure spring security.

Here we have used DelegatingFilterProxy which intercepts http request and pass it to springSecurityFilterChain. springSecurityFilterChain is a bean created by spring with http element used in spring-security.xml. It maintains list of all filters and is responsible for chain of filters.
We are done with changes required for spring security.
Step 6:
It’s time for maven build.
 
Provide goals as clean install (given below) and click on run

Run the application

Step 7:
Right click on project -> run as -> run on server
Select apache tomcat and click on finish
   You will see below screen:

When you click on above link, you will get following login page.

If you put wrong password and try to login, you will get below screen

If you put correct user id and password

Bingo !! you have logged in successfully.


When you click on logout, you will be back to first screen.

Download source code:

click to begin
20KB .zip

Please comment if you have any issues with above post.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *