Friday 7 December 2012

Getting Started With Spring Security

Posted by Naveen Katiyar On 10:49 No comments

Getting Started With Spring Security

Spring Security is a security framework for authentication, authorization and role based authorization of the users.Spring Security Framework provides a lot of facilities to take care of the java web enterprise security management. Its really great security framework that work with Spring IoC or DI to inject the dependencies and securing the java web application.
Following are the some of the important facilities that Spring Security Framework provides to it’s users:
  • User authentication and authorization.
  • Role based authorization control.
  • Easy to configure with database based authentication and authorization.
  • Encrypted password.
  • Form authentication.
  • File bases user authentication and authorization.
  • and a lot more.
This tutorial will show you the way to configure Spring Security with Spring MVC web application to secure mvc pages. We will take an spring mvc web application example in which, we will configure Spring Security to protect a page from outside access.
Tools used :
  • Spring MVC 3.0.3
  • Spring Security 3.0.5
  • Eclipse Indigo 3.7
  • Tomcat 6
  • Jdk 1.6
To understand the example you will need to have prior knowledge of Spring MVC. If you do not know the basics of Spring MVC the go to our Spring MVC Tutorial.

In our example, there is an example of welcome page that is managed by Spring MVC framework. We will configure Spring Security in this example and will make the welcome page secure. User have to authenticate herself to view welcome page.

Configuring web.xml for Spring Security  

<?xml version="1.0" encoding="UTF-8"?>

<b:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:b="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.xsd">
   
    <http realm="Project Realm" auto-config="true">
        <intercept-url pattern="/**" access="ROLE_ADMIN"/>
    </http>

    <authentication-manager>
        <authentication-provider>
            <password-encoder hash="md5"/>
              <user-service>
                  <user name="admin" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_ADMIN"/>
              </user-service>
        </authentication-provider>
    </authentication-manager>
   
</b:beans>



In web.xml, we have configured Spring MVC to manage the request came for the URL “*.htm”. For configuring Spring Security we do the following :
  1. First of all, we have to register org.springframework.web.filter.DelegatingFilterProxy filter in web.xml. This filter manages the securing of the web pages.
  2. The filter will manage the requested URL “/*”. That means all the requests will go through the filter so that it can authenticate the user of particulate web pages that we will configured as secured pages with Spring Security.
  3. Register org.springframework.web.context.ContextLoaderListener listener provided in Spring so that it can configure spring context on server startup.
Creating home page (index.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<jsp:forward page="/welcome.htm"></jsp:forward>




Creating welcome page (welcome.jsp)


<%@ page session="true" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Configuring Spring Security 3 - This is a secure page</title>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
    </head>
    <body>
        <h1>Welcome!</h1><br />
        ${HelloMessage}<br />
    </body>
</html>

Our welcome page is very simple that only shows a message that is stored in model object. The message is  provided by the controller class.

Creating Welcome Controller class (WelcomeController.java)  



package com.naveen.actions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class WelcomeController {
@RequestMapping(value="/welcome",method=RequestMethod.GET)
public ModelAndView sayHello(Model model){
ModelAndView mv = new ModelAndView();
mv.setViewName("welcome");
model.addAttribute("HelloMessage", "Hello World from Spring Security application.");
return mv;
}
}


As you can see annotation driven configuration has been used to make WelcomeController class as a controller and the sayHello method will manage the request for /welcome url.

Spring Securing Configuration file (spring-securily.xml)

After that we will have to create a Spring Security Configuration file, in which have to define the security constrains that are to be applied to our application. You will see a lot of new things in this file. I will explain all the tags one by one make the things clear to you.


<?xml version="1.0" encoding="UTF-8"?>
<!--
- Application context containing authentication, channel
- security and web URI beans.
-
- Only used by "filter" artifact.
-
-->

<b:beans xmlns="http://www.springframework.org/schema/security"
xmlns:b="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.xsd">

<http realm="Project Realm" auto-config="true">
<intercept-url pattern="/**" access="ROLE_ADMIN"/>
</http>

<authentication-manager>
<authentication-provider>
<password-encoder hash="md5"/>
<user-service>
<user name="admin" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>
</b:beans>


  1. <http/> tag is used to define security setting for web application for defining access constrains for pages, defining login pages, login process to use, activate remember me option, customizing session level setting etc. Here we have used only one option i.e.  <intercept-url pattern=“/**” access=“ROLE_ADMIN”/>. <intercept-url/> tag is used to define url patterns to be secure and the definition of the roles who can access them.  In our example all url patters are secured and only user with role ROLE_ADMIN can access the pages.
  2. <authentication-manager/> tag is used to define method of authentication of the user on the basis of that user will be able to access a page.
  3. <authentication-provider/> tag specifies the username and password provider. It can be also a database table. Here we have used hard coded username and password. Password is encrypted in md5 algorithm.
Spring Configuration File (spring-servlet.xml) 

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<context:component-scan base-package="com" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

</beans>


That’s All Folks

The application is completed now. Just run the application in eclipse by pression Alt + Shift + X, R. It will show the login page. 

You would be thinking from where this login page has come,when we have not created any.THis login pagfe is provided by spring security.

WE will learn in another example about how to customize the login form.

Download Source Code

Click here to download source code 

 



0 comments: