Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Thursday, 14 March 2013

What is Spring Security - How to use Spring Security with Spring MVC

In this blog we will come to know about a very useful feature of Spring, today we will dive into Spring Security and will be able to integrate Spring Security with a Spring MVC framework. By the end of this blog we will be able to answer the questions like, what is Spring Security ? and how to implement Spring Security and its features in a Spring MVC application.
In this 'Spring Security integration with Spring MVC hello world application' we will be having a simple Hello controller through which we will implement a default login form provided by Spring Security.

Project Structure 
Lets start our discussion with a quick view of overall project structure. Just start a simple 'Web Application' in Eclipse and create a project structure as shown in the figure below.

what-is-spring-security

Libraries Used 
Here is an snapshot of all required Jar files that is used to create a Spring Security Hello World application in Eclipse. Apart from all basic libraries we need to add thee main libraries to add speing security feature in the application. Required spring security jar files are 'spring-security-core-3.0.8.RELEASE.jar', 'spring-security-web-3.0.8.RELEASE.jar' and 'spring-security-config-3.0.8.RELEASE.jar'.

what-is-spring-security

/WebContent/WEB-INF/web.xml
The very first step to start a web application in Java is always telling the container about the Application structure and behavior and this is done by 'web.xml' file. In order to make our application 'spring-security' driven we need to add some filter entries over here. We need to add a filter class entry for 'DelegatingFilterProxy', this will make all requests pass through the spring-security. Other entries are same we have added a 'SpringServlet' mapping to delegate all requests be handled by spring itself.
<web-app id="WebApp_ID" version="2.4"

    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring MVC Application</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <!-- Spring MVC -->

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <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>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/mvc-dispatcher-servlet.xml,
            /WEB-INF/spring-security.xml
        </param-value>

    </context-param>
    <!-- Spring Security -->

    <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>


/WebContent/index.jsp
Our application starts with a 'index.jsp' welcome file, we have added a forward entry here so that the control can be transfered to pre defined 'spring-security' controller. This will redirect the appllication control to a login form that is automatically provided by spring-security. Please note that we can always use a custom login form instead of one provided by spring security.
<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>
<%response.sendRedirect("spring_security_login"); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

</body>
</html>


/WebContent/WEB-INF/mvc-dispatcher-servlet.xml
We already knows that dispatcher-servlet is core of all spring applications, all bean entries and default package configuration id done here accordingly.
<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:context="http://www.springframework.org/schema/context"
    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.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="com.beingjavaguys.controller" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/view/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>


/WebContent/WEB-INF/spring-security.xml
This configuration file is totally related to 'spring-security' configuration and settings, all custom entries and pre defined things are configured here.
<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.0.xsd
 http://www.springframework.org/schema/security
 http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">

 <http auto-config="true">
  <intercept-url pattern="/welcomePage" access="ROLE_ADMIN" />
  <form-login default-target-url="/welcomePage" />
 </http>

 <authentication-manager>
  <authentication-provider>
   <user-service>
    <user name="beingjavaguys" password="spring@java" authorities="ROLE_ADMIN" />
   </user-service>
  </authentication-provider>
 </authentication-manager>

</beans:beans>


/src/com/beingjavaguys/controller/HelloController.java
A controlled is added here with a action mapping, if the user provides correct login credentials than application controll is moved to controlled and required mapping action is executed. In our case the mapping defined after successfully login is '/welcome'.
package com.beingjavaguys.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/welcomePage")
public class HelloController {

    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        model.addAttribute("message",
                "Welcome to your first Spring Security Example");
        return "Welcome";
    }
}


/WebContent/WEB-INF/view/Welcome.jsp
This is a simple Jsp file that is mapped to '/welcome' url mapping, if everything goes right the user will be able to see this page.
<html>

<head>
<title>Being Java Guys | Spring Security Example</title>
</head>

<body>
    <center>
        <h3>${message}</h3>
        Being Java Guys Team
    </center>
</body>

</html>

Here we are all done with our application coding and configuration, just run your application on server you will get a login form screen like the figure shown below.

spring-security-tutorials

In case the user provided wrong credential, an error message is displayed as shown in below image and this is all done by spring security itself.

spring-security-tutorials

If the user provides correct credentials, in our case username='beingjavaguys' and password = 'spring@java', then the application will move to specified view as shown in the figure below.

spring-security-tutorials

So this was all about spring security, in details 'spring-security' is a very broad term to discuss here in a single blog. But i hope i could make you understand the basics and implementation of it. In our next blogs we will see how to use custom login form and other settings to implement our own logic with 'spring-security'.










Thanks for reading !
Being Java Guys Team

Download "Spring-Security with Spring MVC Example" from "SkyDrive"





8 comments:

  1. good example, thank you!

    ReplyDelete
  2. | think u have to check your security.xml it does not have any security code
    no security implemented

    ReplyDelete
    Replies
    1. Oh, thanks for notice !

      i copied wrong file under security.xml ..just changed to original one :)

      Delete
  3. Very good example, could you please upload one example using MySql please :D

    ReplyDelete
  4. Hi , I would like to use html page instead os jsp.
    How can do it?

    ReplyDelete
  5. Hi , I would like to use html page instead of jsp.
    How can i do it?

    ReplyDelete
  6. how to add css in this project

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft