Spring Security Authorized Access

In this tutorial, you will discuss about authorized access through Spring Security or access control for some of the more secure resources or urls of any enterprise which some special type of authentication just like admin have some more access or authorization than user login. Sometimes you need to secure your page from unauthorized access. Authorized access is the secure access of page through a permitted username and password. For example, the admin section page can only have permission for admin only.

In the below example, we will ensure secure URL access by providing auto generated Login form using Spring Security. User needs to provide correct login credential to view the page. For accessing admin section, you need to provide admin login and password. While for user section, both admin and user login are permitted.

<security:http auto-config="true">
   <security:intercept-url pattern="/admin*" access="ROLE_ADMIN" />
      <security:logout logout-success-url="/admin" />
   <security:intercept-url pattern="/index*" access="ROLE_USER,ROLE_ADMIN" />
      <security:logout logout-success-url="/index" />
</security:http>

It means the user with authority as ROLE_ADMIN can have access to URL /admin . Also, the URL /index is open for both type of users having authority ROLE_USER or ROLE_ADMIN . If non authorized user try to access it, a “http 403 access denied page” will be displayed.

Required Tools used for this Application:
  • Spring MVC 3.0.1
  • Spring Security 3.1.0
  • STS 2.8.1.RELEASE
  • Tomcat 7
  • Jdk 1.7

 To understand this application you have some prior knowledge about the Spring MVC web application.

Step 1: Please download the following more jars for Spring Security Lib from its official site. 
To get started with the implementation, following jars need to be present in the class path of the project.
  • spring-security-acl-3.1.3.RELEASE.jar
  • spring-security-aspects-3.1.3.RELEASE.jar
  • spring-security-cas-3.1.3.RELEASE.jar
  • spring-security-config-3.1.3.RELEASE.jar
  • spring-security-core-3.1.3.RELEASE.jar
  • spring-security-crypto-3.1.3.RELEASE.jar
  • spring-security-ldap-3.1.3.RELEASE.jar
  • spring-security-openid-3.1.3.RELEASE.jar
  • spring-security-remoting-3.1.3.RELEASE.jar
  • spring-security-taglibs-3.1.3.RELEASE.jar
  • spring-security-web-3.1.3.RELEASE.jar
Step 2: Create the project "SpringSecurityAuthorizedAccess" with packages"com.dineshonjava.admin.controller" and create the "AdminController.java" file in this package.

Step 3: Some more folders also create on the "WEB-INF" folder with name libs, views for jars and jsp files respectively. Two files "sdnext-servlet.xml" and "sdnext-security.xml" are created on the "WEB-INF" folder.


Step 4: Configuring web.xml for Spring Security
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <servlet>
  <servlet-name>sdnext</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>sdnext</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/sdnext-*.xml,
  </param-value>
 </context-param>
 
 <welcome-file-list>
  <welcome-file>index</welcome-file>
 </welcome-file-list>
 
 <!-- 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>

In web.xml, we have configured Spring MVC to manage the request came for the URL “*.html”. For configuring Spring Security we do the following :

  1. First of all, we have to register org.springframework.web.filter.DelegatingFilterProxyfilter 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.
Step 5: Creating welcome page (welcome.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>WELCOME TO SECURE AREA</title>
</head>
<body>
 <h1>Message : ${message}</h1> 
 <h1>Author : ${author}</h1> 
 <a href='<c:url value="/j_spring_security_logout" />' > Logout</a>
</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.

Step 6: Creating AdminController class (AdminController.java)
package com.dineshonjava.admin.controller;

import java.security.Principal;

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

/**
 * @author Dinesh Rajput
 *
 */
@Controller
public class AdminController {
 
 @RequestMapping(value = "/admin", method = RequestMethod.GET)
 public String welcomeAdmin(ModelMap model, Principal principal) {
  String username = principal.getName();
  model.addAttribute("author", username);
  model.addAttribute("message", "Hello Spring Security - ADMIN PAGE");
  return "welcome";

 }

 @RequestMapping(value = "/index", method = RequestMethod.GET)
 public String printMessage(ModelMap model, Principal principal) {

  String username = principal.getName();
  model.addAttribute("author", username);
  model.addAttribute("message", "Hello Spring Security - USER LOGIN");
  return "welcome";
 }
}

Step 7: Spring Securing Configuration file (sdnext-security.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:p="http://www.springframework.org/schema/p" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/security
                           http://www.springframework.org/schema/security/spring-security-3.1.xsd">

 <security:http auto-config="true">
  <security:intercept-url pattern="/admin*" access="ROLE_ADMIN" />
  <security:logout logout-success-url="/index" />
  <security:intercept-url pattern="/index*" access="ROLE_USER,ROLE_ADMIN" />
  <security:logout logout-success-url="/index" />
 </security:http>

    <security:authentication-manager>
   <security:authentication-provider>
     <security:user-service>
   <security:user name="user_dineshonjava" password="sweety" authorities="ROLE_USER" />
   <security:user name="admin_dineshonjava" password="sweetu" authorities="ROLE_ADMIN" />
     </security:user-service>
     
   </security:authentication-provider>
 </security:authentication-manager>

</beans>



<security: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.  

1. <security:intercept-url pattern=“/index*” access=“ROLE_USER,ROLE_ADMIN”/>. <security: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 have pattern /index* are secured and only users will role ROLE_USER and ROLE_ADMIN can access the pages.

2. <security:intercept-url pattern=“/admin*” access=“ROLE_ADMIN”/>. <security: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 have pattern /admin* are secured and only admin will role ROLE_ADMIN can access the pages. If you try this page with the ROLE_USER then you cant access the admin page.

3. <security: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 "sweety" and username is "user_dineshonjava" for url patters have pattern /index* as well as we access with Password is "sweetu" and username is "admin_dineshonjava".

For  url patters have pattern /admin* Password is "sweetu" and username is "admin_dineshonjava".

Step 8: Spring Configuration File (sdnext-servlet.xml)
 


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
 
 <context:component-scan base-package="com.dineshonjava.admin" />

 
 <bean id="jspViewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/views/" />
  <property name="suffix" value=".jsp" />
 </bean>
  
</beans>
Step 9: Running the example

Export the example as war and deploy it Tomcat 7 server. While browsing the project you will get the following screen for loging:

Error messages will be displayed if wrong username and password are provided. 
http://localhost:8080/sdnext/spring_security_login?login_error


And if you try to login  with user login(Username- user_dineshonjava, Password-sweety), you will get the below error message :

And if your login is admin login(Username-admin_dineshonjava, Password-sweetu) , you will get the following page :

Now click on the Logot link its lands to the /index page which accessible by both users "user_dineshonjava" as well as "admin_dineshonjava". But here we access this page using the username "user_dineshonjava" and password "sweetu". Get the following.




Download Source Code + Libs
SpringSecurityAuthorizedAccess.zip

References- 
http://www.dineshonjava.com/2013/02/spring-security-form-based-login-example.html
Spring Security
Spring Security documentation


                             <<previous<<             || index  ||         >>next>>

2 comments:

  1. Hi Dinesh, very well explained. How can i retreive the username from a one -to-one relationship.
    Person(id_per, first_name, last_name)<-->Datas(id_per, username, password).
    Thanks a lot!

    ReplyDelete
    Replies
    1. Hi friends,
      Thanks for nice compliment and good comment.

      class Person{
      @id
      private int id_per;
      @Column
      private String first_name;
      @Column
      private String last_name;
      @One to One
      private Datas data;
      }
      }

      Delete