Friday 27 December 2013

Spring Security Introduction : Basic Authentication Example

Introduction

Spring Security is a major module in Spring Distribution. It is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements.

Before going forward lets have an overview of some of the key concepts:

  • Web/HTTP Security - It is the most complex part.It sets up the filters and related service beans used to apply the framework authentication mechanisms, to secure URLs, to render login and error pages and much more.
  • Business Object (Method) Security - It provides options for securing the service layer.
  • AuthenticationManager - It handles authentication requests from other parts of the framework.
  • AccessDecisionManager - It provides access decisions for web and method security. A default one will be registered, but you can also choose to use a custom one, declared using normal Spring bean syntax.
  • AuthenticationProviders - They provide mechanisms against which the authentication manager authenticates users. The namespace provides support for several standard options and also a means of adding custom beans declared using a traditional syntax.
  • UserDetailsService - It is closely related to authentication providers, but often also required by other beans.It is used to provide authentication information.
In this example, the user authentication information is maintained in xml configuration file for spring security.


Setup

This is how the final project structure looks like -



Dependencies

If you are using maven, following are the dependencies which will be required -

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>

These are the minimal set of dependencies for Spring Security. Using additional features will require addition of appropriate project modules.

Configuring web.xml



    SpringSecurity1
    
        /WEB-INF/jsp/index.jsp
    
 
    
        spring
        
            org.springframework.web.servlet.DispatcherServlet
        
        1
    
    
        spring
        /
     
    
    
  
                  org.springframework.web.context.ContextLoaderListener
                
 
 
 
  contextConfigLocation
  
   /WEB-INF/spring-servlet.xml,
   /WEB-INF/spring-security.xml
  
 
 
 
 
  springSecurityFilterChain
  
                  org.springframework.web.filter.DelegatingFilterProxy
                
 
 
 
  springSecurityFilterChain
  /*
 
This provides a hook into the Spring Security web infrastructure. DelegatingFilterProxy is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security. Note that you should not use this bean name yourself. Once you’ve added this to your web.xml, you’re ready to start editing your application context file. Web security services are configured using the <http> element.

Don't forget to include spring-security.xml file for the Context Configuration location.

Configuration : spring-security.xml




 
  
  
  
  
 

 
  
   
    
   
  
 



This is the configuration file where we provide all the spring security configurations. <http> element is the parent for all web-related namespace functionality. The <intercept-url> element defines a patternwhich is matched against the URLs of incoming requests using an ant path style syntax. All the URLs beginning with welcome will be intercepted in this case. It says that we want all URLs matching the pattern '/welcome**' to be secured, requiring the role ROLE_USER to access them, we want to log in to the application using a form with username and password, and that we want a logout URL registered which will allow us to log out of the application.
The access attribute defines the access requirements for requests matching the given pattern. With the default configuration, this is typically a comma-separated list of roles, one of which a user must have to be allowed to make the request.The logout-success-url specifies the URL which will be presented to the user once the user has logged out.

If a form login isn’t prompted by an attempt to access a protected resource, the default-target-url option comes into play. This is the URL the user will be taken to after successfully logging in, and defaults to "/". One can also configure things so that the user always ends up at this page (regardless of whether the login was "on-demand" or they explicitly chose to log in) by setting the always-use-default-targetattribute to "true".


The <authentication-provider> element creates a DaoAuthenticationProvider bean and the <user-service> element creates an InMemoryDaoImpl. All authentication-provider elements must be children of the <authentication-manager> element, which creates a ProviderManager and registers the authentication providers with it.

The configuration above defines two users, their passwords and their roles within the application (which will be used for access control). When a user enters login information, his username and password are matched with those specified in user-service. If successfully authenticated, the mentioned attributes are linked to the user. These attributes decide whether a user is authorized to make certain requests or not.

Setting up the Controller and spring-servlet.xml 

This is my controller.
package com.spring.security;

import javax.servlet.http.HttpServletRequest;

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

@Controller
public class HelloController {

 @RequestMapping(value = "/welcome", method = RequestMethod.GET)
 public String printWelcome(Model model) {
  model.addAttribute("message", "Spring Security says Hello !");
  return "hello";
 }

 @RequestMapping(value = "/login", method = RequestMethod.GET)
 public String getLoginPage(Model model) {
  return "login";
 }

 @RequestMapping(value = "/home", method = RequestMethod.GET)
 public String getHomePage(Model model) {
  return "index";
 }

 @RequestMapping(value = "/logout", method = RequestMethod.GET)
 public String getLogoutPage(Model model, HttpServletRequest req) {
  req.getSession().invalidate();
  return "logout";
 }
}

spring-servlet.xml



 

 

 
  
  
 


Views

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




Insert title here



 

Message : ${message}

Logout
The default logout URL is /j_spring_security_logout, but you can set it to something else using the logout-url attribute.

logout.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>




Logout


 

You have been successfully logged out !

Go back to login page
The URL where you will find the security login page is '/spring_security_login'.

index.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>





Home



 

Home Page

This is a simple home page


Demo

When you try to access '/SpringSecurity1/welcome' you will be prompted with a Spring Security login page. You might be wondering where the login form came from when you were prompted to log in, since we made no mention of any HTML files or JSPs. In fact, since we didn’t explicitly set a URL for the login page, Spring Security generates one automatically, based on the features that are enabled and using standard values for the URL which processes the submitted login, the default target URL the user will be sent to after logging in and so on.






With correct credentials you will be forwarded to the welcome page



An unsuccessful login will result in a Bad Credentials page.

This was a simple example to give you an overview on Spring Security. In my upcoming posts we will be looking into details many other features provided by Spring Security. You can download the source code of this example from here. 

Thanks and Happy coding !


No comments:

Post a Comment