dineshonjava

Difference between @Secured vs @RolesAllowed vs @PreAuthorize in Spring Security

@Secured and @RolesAllowed are the same the only difference is @RolesAllowed is a standard annotation (i.e. not only spring security) whereas @Secured is spring security only.

@PreAuthorize is different in a way that it is more powerful then the other 2. It allows for SpEL expression for a more fine-grained control. Which to use well the simplest thing that could possible work, if you don't need expression etc. go with the standard annotations to limit the dependency on spring classes. But that all is IMHO of course.

Difference between @Secured and @PreAuthorize Annotation in Spring Security

The main difference between @Secured and @PreAuthorize is that @PreAuthorize can work with Spring EL.

Spring Security Annotation Based Hello World Example

In this tutorial of Spring Security Annotation Based Hello World Example, we will take a look into very simple hello world example of spring security annotation based in a Spring MVC environment. In previous tutorial We have seen same example in the Spring Security XML based in a Spring MVC. Here we going to show you how to create application in annotation or java config based spring security configuration.

Here I have used technologies as below :
  • Spring 4.3.5.RELEASE
  • Spring Security 4.2.1.RELEASE
  • STS 3.5.1
  • JDK 1.8
  • Maven 4
  • Tomcat 8 (Servlet 3.x)


In this tutorial I am using total java based configuration for web application as well so here I am using WebApplicationInitializer implementation to load the Spring Application Context file by Context Loader automatically. But this java configuration is required supported in Servlet 3.x container only i.e as of Tomcat 7 and as of Jetty 8.

Maven Dependency for this application
For this application we have following minimum maven dependencies. For Spring Security into web application we have required two jars only spring-security-web.jar and spring-security-context.jar.

<properties>
   <spring.version>4.3.5.RELEASE</spring.version>
   <spring.security.version>4.2.1.RELEASE</spring.security.version>
  </properties>
  
  <dependencies>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>${spring.version}</version>
 </dependency>
 
 <dependency>
     <groupId>org.springframework.security</groupId>
     <artifactId>spring-security-config</artifactId>
     <version>${spring.security.version}</version>
 </dependency>
 
 <dependency>
     <groupId>org.springframework.security</groupId>
     <artifactId>spring-security-web</artifactId>
     <version>${spring.security.version}</version>
 </dependency>
 
 <dependency>
     <groupId>jstl</groupId>
     <artifactId>jstl</artifactId>
     <version>1.2</version>
 </dependency>
  
  </dependencies>

Application Directory Structure
Here I have created web application using Maven as below directory structure for this application.

Spring Security Annotation Based Hello World Example

Spring Security Annotation or Java Configuration
Here we will see how to configure Spring Security in the Spring MVC application based annotation or java configuration. Follow my another tutorial of Spring Security Java based Annotation Configuration for more detail information about all Spring Security annotations and its used in the application.

Let's create a Spring Security configuration file and annotated it with @EnableWebSecurity as below:

SecurityConfig.java

/**
 * 
 */
package com.doj.app.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
 //Override Default configuration in WebSecurityConfigurerAdapter for custom login form and authorize requests
 //We specified multiple URL patterns that any user can access like "/login/".
 //Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN". 
 //Any URL that has not already been matched on only requires that the user be authenticated
 @Override
 protected void configure(HttpSecurity http) throws Exception {
  http
   .authorizeRequests()                                                                
    .antMatchers("/resources/**", "/login").permitAll()                  
    .antMatchers("/admin/**").hasRole("ADMIN")                                      
    .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")            
    .anyRequest().authenticated()                                                   
    .and()
   .formLogin();
 }
 //In memory authentication java configuration
 //Not web-specific
 @Autowired
 public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  auth
   .inMemoryAuthentication() //Adds a UserDetailsManagerConfigurer
    //login, password and supported role
    .withUser("user").password("password").roles("USER").and()
    .withUser("admin").password("dinesh").roles("ADMIN");
 }
}


In the previous example, its equivalent XML configuration file for Spring Security.
applicationContext-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_USER" />
  <security:intercept-url pattern="/*" access="ROLE_USER" />
 </security:http>

    <security:authentication-manager>
   <security:authentication-provider>
     <security:user-service>
   <security:user name="user" password="password" authorities="ROLE_USER" />
   <security:user name="admin" password="dinesh" authorities="ROLE_ADMIN" />
     </security:user-service>
   </security:authentication-provider>
 </security:authentication-manager>

</beans>


Here I have overridden configure(HttpSecurity http) method of WebSecurityConfigurerAdapter class of Spring Security for customization in authorization and authentication mechanism. By default this configure(HttpSecurity http) method of WebSecurityConfigurerAdapter apply the authentication to all application calls or URLs. But here URL like "/resources/**", "/login" permit for all without authentication required by using permitAll() method and URL like "/admin/**" is required a special ADMIN role for accessing it and else URLs of the web application is required authentication only for any ROLE either ADMIN, USER, DB etc..

Note: Access control for more specific URLs like "/admin/**", "/db/**" should be always define first above to the general case like "/**".

Note: As of Spring Security 4.0, @EnableWebMvcSecurity is deprecated. The replacement is @EnableWebSecurity which will determine adding the Spring MVC features based upon the classpath. To enable Spring Security integration with Spring MVC add the @EnableWebSecurity annotation to your configuration.

Loading Spring Security Filters Chain to Container
Spring Security has lot of filters to apply the security to the web application. But but we don't need to configure all filters in to web.xml or ApplicationInitializer class file of the application. Spring Security provides us a Special Filter bean class "SpringSecurityFilterChain" it is responsible for registering all filters into spring application context file as beans. And one more filter of Spring Security, "DelegatingFilterProxy" delegates the request to associated registered bean class into application context file with same name as filter name in the web.xml file.

Let's see the below file that is responsible to loading Spring Security Context file to container.

SecurityWebApplicationInitializer.java

/**
 * 
 */
package com.doj.app.web;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

/**
 * @author Dinesh.Rajput
 *
 */
public class SecurityWebApplicationInitializer extends
  AbstractSecurityWebApplicationInitializer {

}


This class SecurityWebApplicationInitializer.java does not have any body here but it extends AbstractSecurityWebApplicationInitializer, it will load the springSecurityFilterChain automatically define internally by Spring Security Framework. In previous XML based example it's equivalent XML configuration in the web.xml file as below:

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

That is all about the Spring Security Annotation Based basic java configuration for this example. Let's see below file has Spring MVC configuration for this application.

WebMvcConfig.java
/**
 * 
 */
package com.doj.app.config.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.doj.app.web.controller")
public class WebMvcConfig {
 
 @Bean
 public ViewResolver viewResolver(){
  InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
  viewResolver.setPrefix("/WEB-INF/view/");
  viewResolver.setSuffix(".jsp");
  return viewResolver;
 }
}

It's equivalent configuration in the XML based configuration:

<context:component-scan base-package="com.doj.app.web.controller" />

<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/view/" />
 <property name="suffix" value=".jsp" />
</bean>

Let's see WebApplicationInitializer class to load every thing to web container. This is file is equivalent to web.xml file in the XML based application.

ApplicationInitializer.java

/**
 * 
 */
package com.doj.app.web;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.doj.app.config.RootConfig;
import com.doj.app.config.security.SecurityConfig;
import com.doj.app.config.web.WebMvcConfig;

/**
 * @author Dinesh.Rajput
 *
 */
public class ApplicationInitializer extends
  AbstractAnnotationConfigDispatcherServletInitializer {

 @Override
 protected Class<?>[] getRootConfigClasses() {
  return new Class<?>[] { RootConfig.class, SecurityConfig.class };
 }

 @Override
 protected Class<?>[] getServletConfigClasses() {
  return new Class<?>[] { WebMvcConfig.class };
 }

 @Override
 protected String[] getServletMappings() {
  return new String[] {"/"};
 }

}


Finally we have a HomeController of application to handling requests from browser.

package com.doj.app.web.controller;

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

/**
 * @author Dinesh Rajput
 *
 */
@Controller
public class HomeController {
 
 @GetMapping("/")
 public String home(ModelMap model) {
  model.addAttribute("message", "Learn Spring Security Hello World Example with Annotations");
  model.addAttribute("author", "User of Dinesh on Java");
  return "home";
 }
 
 @GetMapping("/admin/")
 public String admin(ModelMap model) {
  model.addAttribute("message", "Create Spring Security Hello World Example with Annotations");
  model.addAttribute("author", "Admin of Dinesh on Java");
  return "admin";
 }
}


Download Source Code of this Spring Security Annotation Example from Git.

Demo

Let's see demo of this example after successfully deployed to the tomcat 7 or 8.
After running server try to access the application then Spring Security will intercept the request and redirect to /login, and a default login form is displayed.

spring-security-demo-login-page

If username and password is incorrect or empty submit then it will display error messages, and Spring Security's ExceptionTranslationFilter will redirect to this URL /login?error.

spring-security-demo-login-page-with-error-messages

If username and password is correct then it will redirect the request to the original requested URL and display the page.

spring-security-demo-home-page

Suppose we have logged in with "user" and "password" as configured above in the Spring Security Configuration, This user has Role "USER" and we are trying to access unauthorized resource of admin, required "ADMIN" role, Spring will display the 403 access denied page.

spring-security-demo-403-page



Spring Security XML Namespace Configuration Example

In this Spring Security Tutorial Series we will take a look how to use Spring Security with XML Namespace Configuration with Example of authentication and access-control using <http>, <intercept-url> namespaces. In my earlier article We have seen Spring Security Java Configuration Annotation Example of Authentication and access control using @Secured, @PreAuthorize and JSR-250 @RolesAllowed annotations. As we know that Spring Security is a very powerful and highly customizable authentication and access-control framework.

Spring Security XML Namespace Configuration
XML Namespace configuration has been available since Spring Security 2.0. In Spring Framework, A namespace element is nothing but it is a more concise way of configuring an individual bean or, more powerfully, to define an alternative configuration syntax. It actually hides the underlying bean definition complexity from the user. For using the spring security namespace in your application context, you need to have the spring-security-config jar on your classpath. And finally you need to add the schema declaration to your application context file as below:

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


web.xml Configuration (Setup DelegatingFilterProxy and springSecurityFilterChain)
FilterChainProxy add a single entry to web.xml and deal entirely with the application context file for managing our web security beans. It is wired using a DelegatingFilterProxy, just like in the example above, but with the filter-name set to the bean name "springSecurityFilterChain". In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security.

Define the single proxy filter
springSecurityFilterChain is a mandatory name
        -Refers to an existing Spring bean with same name

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>17-Spring-Security-XML-Namespace-Config</display-name>
 <servlet>
        <servlet-name>doj</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
         <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>doj</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
 <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>
Spring Security Filter Configuration

Spring Security Namespace Configuration in the Application Context file
Once you’ve added DelegatingFilterProxy and springSecurityFilterChain to your web.xml, you’re ready to start editing your application context file. Web security services are configured using the <http> element.

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

 <context:component-scan base-package="com.doj.app.controller"/>
 
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="suffix" value=".jsp"/>
  <property name="prefix" value="/WEB-INF/view/"/>
 </bean>

 <security:http>
  <security:intercept-url access="hasRole('USER')" pattern="/**" />
  <security:form-login/>
  <security:logout/>
 </security:http>


      <security:authentication-manager>
  <security:authentication-provider>
   <security:user-service>
    <security:user name="admin" password="adminpassword" authorities="ROLE_USER, ROLE_ADMIN" />
    <security:user name="user" password="password" authorities="ROLE_USER" />
   </security:user-service>
  </security:authentication-provider>
 </security:authentication-manager>

</beans>


As according to the above application context file, we want all URLs within our application 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 configuration above defines two users, their passwords and their roles within the application.


  • <security:http> : This element is the parent for all web-related namespace functionality. It is responsible for creating a FilterChainProxy and the filter beans which it uses. Common problems like incorrect filter ordering are no longer an issue as the filter positions are predefined.
  • <security:intercept-url> : This element defines a pattern which is matched against the URLs of incoming requests using an ant path style syntax.
    • Note: You can use multiple <security:intercept-url> elements to define different access requirements for different sets of URLs, but they will be evaluated in the order listed and the first match will be used. So you must put the most specific matches at the top.
  • <security:authentication-manager> : This element creates a ProviderManager and registers the authentication providers with it.
  • <security:authentication-provider> : This element creates a DaoAuthenticationProvider bean.
  • <security:user-service> : This element creates an InMemoryDaoImpl.


Adding Custom Login Form:
Thus far Spring Security generates login form 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.

<security:http pattern="/login" security="none"/>
<security:http pattern="/css/**" security="none"/>
<security:http pattern="/scripts/**" security="none"/> 
<security:http>
 <security:intercept-url pattern="/**" access="hasRole('USER')" />
 <security:form-login login-page="/login"/>
 <security:logout/>
</security:http>
 
<security:authentication-manager>
 <security:authentication-provider>
  <security:user-service>
   <security:user name="admin" password="adminpassword" authorities="ROLE_USER, ROLE_ADMIN" />
   <security:user name="user" password="password" authorities="ROLE_USER" />
  </security:user-service>
 </security:authentication-provider>
</security:authentication-manager>

From Spring Security 3.1 it is now possible to use multiple http elements to define separate security filter chain configurations for different request patterns. It is also possible to have all requests matching a particular pattern bypass the security filter chain completely, by defining a separate http element for the pattern like this /login, "/resources/", "/scripts/", "/css/" etc.

Handling Logouts
When using the <security:logout/>, logout capabilities are automatically applied.
The default is that accessing the URL /logout will log the user out by:

  • Invalidating the HTTP Session
  • Cleaning up any RememberMe authentication that was configured
  • Clearing the SecurityContextHolder
  • Redirect to /login?logout

<security:logout 
    invalidate-session="true" 
    delete-cookies="AppCookies" 
    logout-url="/logout" 
    logout-success-url="/home"/>

Configure Authentication Providers
There are three built in options:

  1. LDAP, 
  2. JDBC, 
  3. in-memory .

In-Memory Authentication Namespace Configuration
<security:authentication-manager>
 <security:authentication-provider>
  <security:user-service>
   <security:user name="admin" password="adminpassword" authorities="ROLE_USER, ROLE_ADMIN" />
   <security:user name="user" password="password" authorities="ROLE_USER" />
  </security:user-service>
 </security:authentication-provider>
</security:authentication-manager>

JDBC Authentication Namespace Configuration
<authentication-manager>
<authentication-provider>
 <jdbc-user-service data-source-ref="dataSource"/>
</authentication-provider>
</authentication-manager>

Where "dataSource" is the name of a DataSource bean in the application context, pointing at a database containing the standard Spring Security user data tables.

Password Encoder
You can also customize how passwords are encoded by exposing a PasswordEncoder as a bean. We can encode passwords using a hash – sha, md5, bcrypt etc.

<security:http pattern="/login" security="none"/>
 <security:http pattern="/css/**" security="none"/>
 <security:http pattern="/scripts/**" security="none"/>
 
 <security:http>
  <security:intercept-url pattern="/**" access="hasRole('USER')" />
  <security:form-login login-page="/login"/>
  <security:logout/>
 </security:http>
 <bean name="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
 <security:authentication-manager>
  <security:authentication-provider>
   <security:password-encoder ref="bcryptEncoder"/>
   <security:user-service>
    <security:user name="admin" password="4e7421b1b8765d8f9406d87e7cc6aa784c4ab97f" authorities="ROLE_USER, ROLE_ADMIN" />
    <security:user name="user" password="d7e6351eaa13189a5a3641bab846c8e8c69ba39f" authorities="ROLE_USER" />
   </security:user-service>
  </security:authentication-provider>
 </security:authentication-manager>

Method Security
From Spring version 2.0 Spring Security provides support to adding security to your service layer methods. Spring Security uses AOP for security at the method level.
– annotations based on Spring annotations or JSR-250 annotations
– Java configuration to activate detection of annotations
- From 3.0 you can also make use of new expression-based annotations.
Typically secure your services
– Do not access repositories directly, bypasses security (and transactions)

EnableGlobalMethodSecurity
<global-method-security>- This element is used to enable annotation-based security in your application. The following declaration would enable support for Spring Security’s @Secured:
<global-method-security secured-annotations="enabled" />

import org.springframework.security.annotation.Secured;

public class ItemManagerService {
@Secured("IS_AUTHENTICATED_FULLY")
public Item findItem(long itemNumber) {
...
}
}
We can also use

  • @Secured("ROLE_MEMBER")
  • @Secured({"ROLE_MEMBER", "ROLE_USER"})


Note: Spring 2.0 syntax, so not limited to roles. SpEL not supported.

Enable Method Security - JSR-250
Support for JSR-250 annotations can be enabled using.
<global-method-security jsr250-annotations="enabled" />

import javax.annotation.security.RolesAllowed;

public class ItemManagerService {
@RolesAllowed({"ROLE_MEMBER", "ROLE_USER"})
public Item findItem(long itemNumber) {
...
}
}

Note: Only supports role-based security – hence the name

Method Security with SpEL
To use the new expression-based syntax, you would use

<global-method-security pre-post-annotations="enabled" />

public interface ItemManagerService {

@PreAuthorize("isAnonymous()")
public Item findItem(Long itemNumber);

@PreAuthorize("isAnonymous()")
public Item[] findItems();

@PreAuthorize("hasAuthority('ROLE_USER')")
public Item post(Item item);
}

Adding Security Pointcuts using protect-pointcut
The use of protect-pointcut is particularly powerful, as it allows you to apply security to many beans with only a simple declaration. Consider the following example:

<global-method-security>
<protect-pointcut expression="execution(* com.doj.app.*Service.*(..))"
 access="ROLE_USER"/>
</global-method-security>

This will protect all methods on beans declared in the application context whose classes are in the com.doj.app package and whose class names end in "Service". Only users with the ROLE_USER role will be able to invoke these methods.

Download Java Based Configuration Example from Git

Spring Security XML Namespace Configuration Example



Spring Security Java Configuration Annotation Example

In this Spring Security tutorial, we’ll take a look at Spring Security Java Configuration. Spring Security provides authentication and access-control features for the web layer of an application. Spring Security is a very powerful and highly customizable authentication and access-control framework. Spring security provides support for authentication and access control via configuring lot of filters in a order to filter any request before accessing any secured resource.

Here we will describe how to configure Spring Security in the web application by java based configuration instead of XML namespace configuration. Spring Security provides support for Java Based Configuration from Spring Security 3.2. Java developers can easily configure Spring Security in the web application by Java based without the use of any XML.

Spring Security's web infrastructure is nothing but it is collection of standard servlet filters. There is no web components exists into Spring Security infrastructure as like Spring MVC, Struts etc. Spring Security only provides filter to the requests, doesn't matter whether requests are coming from any browser, device, AJAX, REST etc.


Even Spring Security provide application security but it is not a panacea which will solve all security issues. So we have also take care about the many potential vulnerabilities such as cross-site scripting, request-forgery when application designed. Let's see this java based configuration with an example. Before example let recall some spring security terms with meaning.

Spring Security Terms
  • Principal– User, device or system that performs an action
  • Authentication– Establishing that a principal’s credentials are valid
  • Authorization– Deciding if a principal is allowed to perform an action
  • Secured item– Resource that is being secured
Spring Security Flow in the Application
Let's take a look into flow of Spring Security in the Application with example. In this article we just setup Spring Security into a simple web application. After setup Spring Security will work as below picture.

Spring Security Java Based Configuration

According to the above picture one thread want to access one secured resource at web but security applied by the spring security interceptors so thread should be authenticated and also it have proper access-control to access this secured resource. That means Spring Security provides two main mechanisms one is Authentication and another is Authorization. Authentication provided by AuthenticationManager and access decision taken by AccessDecisionManager in the Spring Security. Irrespective of the authentication mechanism, Spring Security provides a deep set of authorization capabilities. There are three main areas of interest: authorizing web requests, authorizing whether methods can be invoked and authorizing access to individual domain object instances.

1. Setup Spring Security to Web Application
1.1 Setup of Spring Security Filter (DelegatingFilterProxy)
As I told you already that Spring Security provides lot of filters in the infrastructure. When using servlet filters, you obviously need to declare them in your web.xml, or they will be ignored by the servlet container. These filter classes are also Spring beans in Spring Security so we can define these filter beans in the application context and thus we can take advantage of Spring’s rich dependency-injection facilities and lifecycle interfaces.

But question is that how to apply these spring security filters to intercepting the requests if you configure these filters in your application context file instead of web.xml? Don't worry Spring Security also provides solution for this problem. It provides you a special DelegatingFilterProxy filter. Spring’s DelegatingFilterProxy provides the link between web.xml and the application context. So each filter in Spring Security has own corresponding delegating filter to provide the link between web.xml and the application context.  DelegatingFilterProxy delegates the Filter 's methods through to a bean which is obtained from the Spring application context.

<filter>
<filter-name>myFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

DelegatingFilterProxy delegates the filter's methods to a bean in the application context only when the bean must implement javax.servlet.Filter and it must have the same name as that in the filter-name element.

1.2 Setup Order of Spring Security Filters Chain (FilterChainProxy)
As we know Spring Security has lot of filters to be configured in a specific order in the web.xml by using corresponding delegating filter. But it would be cumbersome task to maintain web.xml in case of robust application, have a lot of filters. Spring Security provides us a FilterChainProxy bean to maintain the order filters as below.

<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<constructor-arg>
 <list>
 <sec:filter-chain pattern="/restful/**" filters="
  securityContextPersistenceFilterWithASCFalse,
  basicAuthenticationFilter,
  exceptionTranslationFilter,
  filterSecurityInterceptor" />
 <sec:filter-chain pattern="/**" filters="
  securityContextPersistenceFilterWithASCTrue,
  formLoginFilter,
  exceptionTranslationFilter,
  filterSecurityInterceptor" />
 </list>
</constructor-arg>
</bean>

Now add the delegating filter for FilterChainProxy to web.xml filter name should same as bean name in the application context "filterChainProxy" as below:

<filter>
<filter-name>filterChainProxy</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>filterChainProxy</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

FilterChainProxy add a single entry to web.xml and deal entirely with the application context file for managing our web security beans. It is wired using a DelegatingFilterProxy, just like in the example above, but with the filter-name set to the bean name "filterChainProxy". The filter chain is then declared in the application context with the same bean name.

Spring Security Filter Configuration

2. Java Based Spring Security Configuration Example
Java configuration creates a Servlet Filter known as the springSecurityFilterChain which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc) within your application. Spring Security provides an abstract class AbstractSecurityWebApplicationInitializer to ensure register the springSecurityFilterChain with the war Filter for every URL in your application. It will be work only on Servlet 3.0+ environment.

2.1 Setup DelegatingFilterProxy and FilterChainProxy

2.1.1 Spring Security Configuration in the Application Context
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Bean
  public UserDetailsService userDetailsService() {
 InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
 manager.createUser(User.withUsername("user").password("password").roles("USER").build());
 return manager;
  }
  @Override
  protected void configure(HttpSecurity http) throws Exception {

  }
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

  }
}

2.1.2 AbstractSecurityWebApplicationInitializer without Existing Spring
Suppose if you are using Spring Security in non Spring application then you will need to pass in the SecurityConfig into the superclass to ensure the configuration is picked up.
/**
 * 
 */
package com.doj.app.web;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

/**
 * @author Dinesh.Rajput
 *
 */
public class SecurityWebApplicationInitializer extends
  AbstractSecurityWebApplicationInitializer {
   public SecurityWebApplicationInitializer() {
  super(SecurityConfig.class);
   }

}


SecurityWebApplicationInitializer class do automatically register the springSecurityFilterChain Filter for every URL in your application and also add a ContextLoaderListener that loads the SecurityConfig class.

2.1.3 AbstractSecurityWebApplicationInitializer with Spring MVC
Suppose if you are using Spring in your application then you can register Spring Security with the existing ApplicationContext.
/**
 * 
 */
package com.doj.app.web;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

/**
 * @author Dinesh.Rajput
 *
 */
public class SecurityWebApplicationInitializer extends
  AbstractSecurityWebApplicationInitializer {

}

This would simply only register the springSecurityFilterChain Filter for every URL in your application. After that we would ensure that SecurityConfig was loaded in our existing ApplicationInitializer.

2.2 HttpSecurity (authorizeRequests())
Thus far our SecurityConfig file only contains default information about how to authenticate our users. In above our configuration file SecurityConfig extends WebSecurityConfigurerAdapter class for more control over the default configuration. WebSecurityConfigurerAdapter provides a default configuration in the configure(HttpSecurity http) method that is why all users require to be authenticated for accessing any URLs of web application. But we can override this method as below:

//1. Default
//Default configuration in WebSecurityConfigurerAdapter
protected void configure(HttpSecurity http) throws Exception {
 http
  .authorizeRequests()
   .anyRequest().authenticated()
   .and()
  .formLogin()
   .and()
  .httpBasic();
}
The default configuration above:

  • Ensures that any request to our application requires the user to be authenticated
  • Allows users to authenticate with form based login
  • Allows users to authenticate with HTTP Basic authentication


2.3 Custom Login Form Java Configuration
Spring Security generates login form 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.

//2. Custom Login Form
//Override Default configuration in WebSecurityConfigurerAdapter for custom login form instead auto generated login form by spring security
//The updated configuration specifies the location of the log in page.
//We must grant all users (i.e. unauthenticated users) access to our log in page
protected void configure(HttpSecurity http) throws Exception {
 http
  .authorizeRequests()
   .anyRequest().authenticated()
   .and()
  .formLogin()
   .loginPage("/login") //specifies the location of the log in page
   .permitAll(); //allows granting access to all users for all URLs
}

And login file as below login.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:url value="/login" var="loginUrl"/>
<form action="${loginUrl}" method="post">       
 <c:if test="${param.error != null}">        
  <p>
   Invalid username and password.
  </p>
 </c:if>
 <c:if test="${param.logout != null}">       
  <p>
   You have been logged out.
  </p>
 </c:if>
 <p>
  <label for="username">Username</label>
  <input type="text" id="username" name="username"/> 
 </p>
 <p>
  <label for="password">Password</label>
  <input type="password" id="password" name="password"/> 
 </p>
 <input type="hidden"                        
  name="${_csrf.parameterName}"
  value="${_csrf.token}"/>
 <button type="submit" class="btn">Log in</button>
</form>

2.4. Authorize Requests

  • Adds specific authorization requirements to URLs
  • Evaluated in the order listed – first match is used, put specific matches first

//3. Customization to authorize request
//Override Default configuration in WebSecurityConfigurerAdapter for custom login form and authorize requests
//We specified multiple URL patterns that any user can access like "/resources/", "/scripts/", "/css/" etc.
http
.authorizeRequests()
.antMatchers("/css/**","/images/**","/scripts/**").permitAll()
.antMatchers("/accounts/edit*").hasRole("ADMIN")
.antMatchers("/accounts/account*").hasAnyRole("USER",”ADMIN”)
.anyRequest().authenticated()                                                   
.and()
.formLogin()
.loginPage("/login") 
.permitAll();
}
  • Any URL that starts with "/accounts/edit" will be restricted to users who have the role "ROLE_ADMIN".
  • Any URL that starts with "/accounts/account" requires the user to have both "ROLE_ADMIN" and "ROLE_USER".
  • Any URL that has not already been matched on only requires that the user be authenticated


2.5. Handling Logouts
When using the WebSecurityConfigurerAdapter, logout capabilities are automatically applied.
The default is that accessing the URL /logout will log the user out by:

  • Invalidating the HTTP Session
  • Cleaning up any RememberMe authentication that was configured
  • Clearing the SecurityContextHolder
  • Redirect to /login?logout


protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/aaa*").hasRole("ADMIN")
.and() // method chaining!
.formLogin() // setup form-based authentication
.loginPage("/login.jsp") // URL to use when login is needed
.permitAll() // any user can access
.and() // method chaining!
.logout() // configure logout
.permitAll(); // any user can access
}

2.5.1. LogoutHandler
Generally, LogoutHandler implementations indicate classes that are able to participate in logout handling. They are expected to be invoked to perform necessary clean-up.

2.5.2. LogoutSuccessHandler
The LogoutSuccessHandler is called after a successful logout by the LogoutFilter, to handle e.g. redirection or forwarding to the appropriate destination. Note that the interface is almost the same as the LogoutHandler but may raise an exception.

2.6. Configure Authentication
Thus far we have only taken a look at the most basic authentication configuration. Let’s take a look at a few slightly more advanced options for configuring authentication. Spring Security provides various Authentication Provider as below:
  • DAO Authentication provider is default
    • Expects a UserDetailsService implementation to provide credentials and authorities
      • Built-in: In-memory (properties), JDBC (database), LDAP
      • Custom
  • Or define your own Authentication provider
    • Example: to get pre-authenticated user details when using single sign-on
      • CAS, TAM, SiteMinder
2.6.1 Authentication provider: Use a UserDetailsManagerConfigurer
– Three built in options: LDAP, JDBC, in-memory (for quick testing)
– Or use your own UserDetailsService implementation

In-Memory Authentication Java Configuration
//In memory authentication java configuration
//Not web-specific
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication() //Adds a UserDetailsManagerConfigurer
//login, password and supported role
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("adminpassword").roles("ADMIN").and()
.withUser("dinesh").password("support").roles("SUPPORT");
}

JDBC Authentication Java Configuration
//JDBC Authentication
//Provides default queries
//– SELECT username, password, enabled FROM users WHERE username = ?
//– SELECT username, authority FROM authorities WHERE username = ?
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}

We can customize the default queries by using following methods

  • usersByUsernameQuery()
  • authoritiesByUsernameQuery()
  • groupAuthoritiesByUsername()


//JDBC Authentication
//Provides default queries
//– SELECT username, password, enabled FROM users WHERE username = ?
//– SELECT username, authority FROM authorities WHERE username = ?
//We can customize the default queries by using following methods
//usersByUsernameQuery()
//authoritiesByUsernameQuery()
//groupAuthoritiesByUsername()
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.usersByUsernameQuery("SELECT username, password, enabled FROM users WHERE username = ?")
.authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username = ?")
.dataSource(dataSource);
}

2.6.2 Password Encoder
You can also customize how passwords are encoded by exposing a PasswordEncoder as a bean. We can encode passwords using a hash – sha, md5, bcrypt etc.
//SHA-256 encoding
auth.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(new StandardPasswordEncoder());

2.6.3 Use Salting in Password Encoder
Secure passwords using a well-known string known as a 'salt', makes brute force attacks harder
//Encoding with salt
auth.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(new StandardPasswordEncoder("sodium-chloride"));

Note: Authorization is not affected by changes to Authentication!

2.7. Configure Multiple HttpSecurity
We can configure multiple HttpSecurity instances. The key is to extend the WebSecurityConfigurationAdapter multiple times.

2.8. Method Security
From Spring version 2.0 Spring Security provides support to adding security to your service layer methods. Spring Security uses AOP for security at the method level.
– annotations based on Spring annotations or JSR-250 annotations
– Java configuration to activate detection of annotations
- From 3.0 you can also make use of new expression-based annotations.
Typically secure your services
– Do not access repositories directly, bypasses security (and transactions)

2.8.1 EnableGlobalMethodSecurity
We can enable annotation-based security using the @EnableGlobalMethodSecurity annotation on any @Configuration instance.

2.8.2 Enable Method Security - JSR-250
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class MethodSecurityConfig {
// ...
}

import javax.annotation.security.RolesAllowed;

public class ItemManagerService {
@RolesAllowed({"ROLE_MEMBER", "ROLE_USER"})
public Item findItem(long itemNumber) {
...
}
}
Note: Only supports role-based security – hence the name

2.8.3 Enable Spring Security’s @Secured annotation
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig {
// ...
}

import org.springframework.security.annotation.Secured;

public class ItemManagerService {
@Secured("IS_AUTHENTICATED_FULLY")
public Item findItem(long itemNumber) {
...
}
}
We can also use

  • @Secured("ROLE_MEMBER")
  • @Secured({"ROLE_MEMBER", "ROLE_USER"})


Note: Spring 2.0 syntax, so not limited to roles. SpEL not supported.

2.8.4 Method Security with SpEL

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig {
// ...
}

public interface ItemManagerService {

@PreAuthorize("isAnonymous()")
public Item findItem(Long itemNumber);

@PreAuthorize("isAnonymous()")
public Item[] findItems();

@PreAuthorize("hasAuthority('ROLE_USER')")
public Item post(Item item);
}

Download Java Based Configuration Example

Source Code of Example from Git.


Spring-Security-java-based-configuration-example

Summary

  • Spring Security secure URLs using a chain of Servlet filters and methods on Spring beans using AOP proxies
  • Out-of-the-box setup usually sufficient – you define:
    • – URL and/or method restrictions
    • – How to login (typically using an HTML form)
    • – Supports in-memory, database, LDAP credentials (and more)
    • – Password encryption using familiar hashing techniques
    • – Support for security tags in JSP views





Spring Security Interview Questions and Answers

Spring Security Interview Questions and Answers

In this Spring security interview questions and answers tutorial I have selected some important question and their answers. Spring Security is one of the powerful and highly customizable authentication and access-control framework. Spring security provide Authentication and Authorization mechanism. Read my Spring Security Tutorial in detail to getting good understating into Spring Security before going to interview questions.


What is the delegating filter proxy?
Spring’s DelegatingFilterProxy provides the link between web.xml and the application context. In Spring Security, the filter classes are also Spring beans defined in the application context and thus able to take advantage of Spring’s rich dependency-injection facilities and lifecycle interfaces.

<filter>
<filter-name>myFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

What is the security filter chain?
In Spring Security you have a lot of filters for web application and these filters are Spring Beans. Each Spring security filter bean that require in your application you have to declare in your application context file and as we know that filters would be applied to application only when they would be declared on web.xml. Now DelegatingFilterProxy comes into picture for delegating the request to fillter which declared into application context file by adding a corresponding DelegatingFilterProxy entry to web.xml for each filter and we have to make sure about ordered, it should be define correctly, but this would be cumbersome and would clutter up the web.xml file quickly if you have a lot of filters. FilterChainProxy lets us add a single entry to web.xml and deal entirely with the application context file for managing our web security beans.

<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<constructor-arg>
 <list>
 <sec:filter-chain pattern="/restful/**" filters="
  securityContextPersistenceFilterWithASCFalse,
  basicAuthenticationFilter,
  exceptionTranslationFilter,
  filterSecurityInterceptor" />
 <sec:filter-chain pattern="/**" filters="
  securityContextPersistenceFilterWithASCTrue,
  formLoginFilter,
  exceptionTranslationFilter,
  filterSecurityInterceptor" />
 </list>
</constructor-arg>
</bean>

Mandatory Filter Name Main Purpose?

  1. SecurityContextIntegrationFilter - Establishes SecurityContext and maintains between HTTP requests
  2. LogoutFilter - Clears SecurityContextHolder when logout requested
  3. UsernamePasswordAuthenticationFilter - Puts Authentication into the SecurityContext on login request
  4. ExceptionTranslationFilter - Converts SpringSecurity exceptions into HTTP response or redirect
  5. FilterSecurityInterceptor - Authorizes web requests based on on config attributes and authorities


Are you able to add and/or replace individual filters?
Spring Security maintains a filter chain internally where each of the filters has a particular responsibility and filters are added or removed from the configuration depending on which services are required.

Is it enough to hide sections of my output (e.g. JSP-Page)?
No, because we cannot readily reverse engineer what URL is mapped to what controller endpoint as controllers can rely on headers, current user, etc to determine what method to invoke.
JSP Tag Libraries- Spring Security has its own taglib which provides basic support for accessing security information and applying security constraints in JSPs.

Why do you need the intercept-url?
intercept-url element is used to define the set of URL patterns that the application is interested in and to configure how they should be handled.

<intercept-url pattern='/secure/**' access='ROLE_A,ROLE_B'/>

In which order do you have to write multiple intercept-url's?
When matching the specified patterns defined by element intercept-url against an incoming request, the matching is done in the order in which the elements are declared. So the most specific patterns should come first and the most general should come last.

<intercept-url pattern='/secure/a/**' access='ROLE_A'/>
<intercept-url pattern='/secure/b/**' access='ROLE_B'/>
<intercept-url pattern='/secure/**' access='ROLE_USER'/>

Why do you need method security? What type of object is typically secured at the method level.
Spring Security uses AOP for security at the method level
– annotations based on Spring annotations or JSR-250 annotations
– Java configuration to activate detection of annotations
It typically secure your services
– Do not access repositories directly, bypasses security (and transactions)

Is security a cross cutting concern? How is it implemented internally?
Yes, Spring Security is a cross cutting concern. Spring security is also using Spring AOP internally.

What do @Secured and @RolesAllowed do? What is the difference between them?
@Secured and @RolesAllowed both annotation provide method level security in to Spring Beans. @Secured is Spring Security annotation from version 2.0 onwards Spring Security. But @RolesAllowed is JSR 250 annoatation. Spring Security provides the support for JSR 250 annotation as well for method level security. @RolesAllowed provides role based security only.

What is a security context?
Security context in Spring Security includes details of the principal currently using the application. Security context is always available to methods in the same thread of execution, even if the security context is not explicitly passed around as an argument to those methods.

How is a Principal defined?
Inside the SecurityContextHolder we store details of the principal currently interacting with the application. Spring Security uses an Authentication object to represent this information.

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}

What is authentication and authorization? Which must come first?

  • Authentication – Establishing that a principal’s credentials are valid
  • Authorization – Deciding if a principal is allowed to perform an action

Authentication comes first before Authorization because authorization process needs princial object with authority votes to decide user allow to perform a action for secured resource.

In which security annotation are you allowed to use SpEL?
They are @PreAuthorize, @PreFilter, @PostAuthorize and @PostFilter. These annotations support expression attributes to allow pre and post-invocation authorization checks and also to support filtering of submitted collection arguments or return values
Method security is a bit more complicated than a simple allow or deny rule. Spring Security 3.0 introduced some new annotations in order to allow comprehensive support for the use of expressions.

<global-method-security pre-post-annotations="enabled"/>

@PreAuthorize("hasRole('USER')")
public void create(Contact contact); 

Does Spring Security support password hashing? What is salting?
Yes, Spring Security provides support for password hashing. The salt is used to prevent dictionary attacks against the key in the event your encrypted data is compromised.



Top Exception handling Best Practices in Java

Exception handling in a robust application is very important part. It is not part of functional requirement of any product but it is necessary to handle any ill condition like connection not available, resource not found, invalid input, null input and so on. In this best practices tutorial , I will discuss some little known practices which must be considered while handling exceptions in a robust application. Java provides many ways to handle exceptions like using try, catch and finally keyword. For more information about java exception handling follow this link. In Java we can also create new exceptions and throw them using throw and throws keyword.

In this java exception handling best practices tutorial I have mention near about top 10 to 20 java best practices to write exception handling code. Before going to read this tutorial learn when to use checked vs unchecked exceptions in Java.

Type of Exceptions in Java

  1. Checked Exceptions
  2. Unchecked Exceptions.

Checked Exceptions
These are the type of exceptions for which the compiler checks to ensure that your code is prepared for handling such exceptions. These are the exceptions that you can expect to occur frequently and you must handle them in your code. The conditions that generate such exceptions are generally outside the control of your program and they can occur in a correct program. But you can anticipate them and thus you must write code to deal with them. Programmatically, checked exceptions are the instances of the Exception class or one of its subclasses, excluding RuntimeException subtree.

Unchecked Exceptions
The compiler does not check for such type of exceptions. Unchecked Exceptions comprise of run time exceptions (of type RuntimeException or its subclasses) and errors (of type Error or its subclasses). Runtime Exceptions occur due to program bugs and include exceptions such as division by zero and invalid array indexing.

Top Exception handling Best Practices in Java


Java Exception Handling Best Practices

Use Checked Exception for Resolvable error and Unchecked Exception for run-time error.
Use Checked Exception on these conditions that generate such exceptions are generally outside the control of your program and they can occur in a correct program. Unchecked Exceptions comprise of run time exceptions (of type RuntimeException or its subclasses) and errors (of type Error or its subclasses). Runtime Exceptions occur due to program bugs and include exceptions such as division by zero and invalid array indexing. You can not recover from an unchecked exception and you are not required to handle such type of exceptions either, but still you can do so if you want.

Declare the specific checked exceptions that your method can throw
Always declare the specific checked exceptions that your method can throw. Suppose there are many such checked exceptions, you should probably wrap them in your own user defined exception and add information to in exception message. You can also use comma between multiple exceptions throws.

public void method() throws Exception { //Incorrect way
}

public void method() throws SpecificException1, SpecificException2 { //Correct way
}

Never throw any exception from finally block
Finally block used for clean up operation and never throw any exception in this block. If clean up operation throw any exception then second exception will come out of method and the original first exception i.e. correct reason will be lost forever. In such condition you can also handle exception in the finally block.

try {
  method();  //Throws exception One
} finally {
  cleanUp();    //If finally also threw any exception the exception One will be lost forever
}

Close or release resource in finally block
Always release all resources after successfully completion or any occurring any exception between the process. So functionality like release resource, close connection of DB or Network. This is a well known best practice in Java. Closing resources in finally block guarantees that precious and scarce resource released properly in case of normal and aborted execution, guaranteed by finally block.

Use finally blocks instead of catch blocks if you are not going to handle exception
If you don't want to handle exception then always finally block with try instead of using try-catch. This is also a good practice.

try {
  doSomething(); 
} finally {
  cleanUp();    //do cleanup here
}

If above code you are accessing some method doSomething() but this method may throw some exception which you do not want to handle in own calling method, but still want some cleanup in case exception occur, then do this cleanup in finally block.

Always include all information about an exception in single log message
Don’t do this:
LOGGER.debug("Using cache sector A");
LOGGER.debug("Using retry sector B");

Do it like this:

LOGGER.debug("Using cache sector A, using retry sector B");

Throw only relevant exception from a method
Always throw relevant exception from a method because it is important to keep application clean. Suppose a method which tries to make connection to DB if you throws NullPointerException then it will not give any relevant information to user. So either you could predefined relevant exception or you could make own custom exception.

Always provide meaning full message on Exception
Always provide meaning full message of Exception to the logs because meaning full message helps to developer to find problem in the application. Always try to provide precise and factual information here. For example, compare these two Exception messages for IllegalArgumentException :

message 1: "Incorrect argument for method"
message 2: "Illegal value for ${argument}: ${value}

first one just says that argument is illegal or incorrect, but second one include both name of argument and its illegal value which is important to point out cause of error.

Avoid empty catch blocks
Never use empty catch block because it not just hides the Errors and Exception, but also may leave your object in unusable or corrupt state.

Never swallow the exception in catch block
This point is also same as leaving empty catch block when handling the exception. Return null from catch block instead of handling the exception, it is cause of losing the error cause forever.

catch (NoSuchMethodException e) {
   return null;
}


Use template methods for repeated try-catch
For repeated catch block of same code in the many places in the application increase the duplicity of code, so always make a template method of this code and use this template method.

class DBUtil{
    public static void closeConnection(Connection conn){
        try{
            conn.close();
        } catch(Exception ex){
            //Log Exception - Cannot close connection
        }
    }
}

public void dataAccessCode() {
    Connection conn = null;
    try{
        conn = getConnection();
        ....
    } finally{
        DBUtil.closeConnection(conn);
    }
}


Never use exceptions for flow control in your program
Exceptions are only erroneous condition in the application code but sometime developer use it as a flow control. Never do that.

try{
    conn.close();
} catch(Exception ex){
    //Writing application logic here
}

Always clean up after handling the exception
Resources like DB connection, Network connections etc. should cleaned up after code execution either successfully completed or throwing any exceptions. If the API you are invoking uses only unchecked exceptions, you should still clean up resources after use, with try – finally blocks.

Always catch only those exceptions that you can actually handle

catch (NoSuchMethodException e) {
   throw e; //Avoid this as it doesn't help anything
}

If you can handle an exception then catch it otherwise re-throw it.

Converting Checked Exception into RuntimeException
This is one of best practices of Exception Handling, many of frameworks like Spring adopt it for handling exception. According to it framework converts checked exception into RuntineException. For example in Spring JDBC framework has converted exception like SQLException wrapped into DataAccessException, an unchecked Exception. This Java best practice provides benefits, in terms of restricting specific exception into specific modules, like SQLException into DAO layer and throwing meaningful RuntimeException to client layer.

Including cause of Exception in stack-trace
Java Exception class provides getCause() method to retrieve cause which can be used to provide more information about root cause of Exception. This Java best practice helps a lot while debugging or troubleshooting an issue.

Document Exception thrown by any method
Should always make document for all exceptions which a piece of code may throw at runtime. This becomes increasingly important if you are writing API or public interface. With proper documentation of Exception thrown by any method you can potentially alert anyone who is using it.