Wednesday, January 24, 2018

Spring 4 Security Basic Example

In this post, I am going to demonstrate Spring Security 4 usage to secure a Spring MVC web application, securing URL access with authentication. We will develop a simple example to learn Spring Security 4 basics. This post uses Spring Annotation-based configuration for Servlet 3.0 containers (So we don't need web.xml). So in this application, we are going to follow zero XML configuration.

Spring Security is a lightweight security framework that provides authentication and authorization support in order to Secure Spring-based applications. It integrates well with Spring MVC and comes bundled with popular security algorithm implementations. Today I am going to show Spring Security 4 basics & advanced usage, securing URL, view’s & methods in your Spring MVC/Hibernate based application. Let’s get started.

Following technologies being used:

  • Spring 4.3.13.RELEASE
  • Spring Security 4.2.3.RELEASE
  • Maven 3.3.9
  • JDK 1.8
  • Tomcat 8.0.21
  • Eclipse/STS (Based on your preference)

Project directory structure:



























Updating pom.xml to include required dependencies:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.javajagran</groupId>
<artifactId>Spring-Security-Annotation-Example</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Spring-Security-Annotation-Example Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.3.13.RELEASE</spring.version>
<springsecurity.version>4.2.3.RELEASE</springsecurity.version>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springsecurity.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springsecurity.version}</version>
</dependency>

<!-- java servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>Spring-Security-Annotation-Example</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>Spring-Security-Annotation-Example</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>


The first thing to notice here is the maven-war-plugin declaration. As we are using full annotation configuration, we don’t even use web.xml so we will need to configure this plugin in order to avoid maven failure to build war package. Along with that, we have also included JSP/Servlet/JSTL dependencies which we will be needing as we are going to use servlet API and JSTL view in our code.


Adding Spring Security Configuration Class

The first and foremost step to add spring security in our application is to create Spring Security Java Configuration. This 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 login form, etc) within our application.

org.javajagran.springsecurity.configration.SecurityConfiguration

package org.javajagran.springsecurity.configration;

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;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("java").password("jagran123").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("admin123").roles("ADMIN");
auth.inMemoryAuthentication().withUser("manager").password("manager123").roles("ADMIN", "MANAGER");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home").permitAll()
                                                       .antMatchers("/admin/**").access("hasRole('ADMIN')")
                                                       .antMatchers("/manager/**").access("hasRole('ADMIN') and hasRole('MANAGER')")
                                                       .and().formLogin().and().exceptionHandling().accessDeniedPage("/access_denied");
}
}

Method configureGlobalSecurity in above class configures AuthenticationManagerBuilder with user credentials and allowed roles. This AuthenticationManagerBuilder creates AuthenticationManager which is responsible for processing any authentication request. Notice that in above example, we have used in-memory authentication while you are free to choose from JDBC, LDAP and other authentications.

The overridden Method Configure configures HttpSecurity which allows configuring web-based security for specific HTTP requests. By default, it will be applied to all requests, but can be restricted using requestMatcher(RequestMatcher)/antMathchers or other similar methods.

In above configuration, we say that URL’s ‘/’ & ‘/home’ are not secured, anyone can access them. URL ‘/admin/**’ can only be accessed by someone who has ADMIN role. URL ‘/manager/**’ can only be accessed by someone who has both ADMIN and MANAGER roles.

Method formLogin provides support for form-based authentication and will generate a default form asking for user credentials. You are allowed to configure your own login form. We will see examples for the same in subsequent posts.

We have also used exceptionHandling().accessDeniedPage() which in this case will catch all 403 (HTTP access denied code) exceptions and display our user-defined page instead of showing default HTTP 403 page.

Registering the springSecurityFilter with war

Below specified initializer class registers the springSecurityFilter (class SecurityConfiguration) with application war.

org.javajagran.springsecurity.configration.SecurityWebApplicationInitializer

package org.javajagran.springsecurity.configration;

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

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{ }

Adding Controller

org.javajagran.springsecurity.configration.SpringSecurityExampleController

package org.javajagran.springsecurity.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SpringSecurityExampleController {

@RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String homePage(ModelMap model) {
model.addAttribute("msg", "Hi, Welcome to Java Jagran");
return "home";
}

@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(ModelMap model) {
model.addAttribute("username", getPrincipal());
return "admin";
}

@RequestMapping(value = "/manager", method = RequestMethod.GET)
public String dbaPage(ModelMap model) {
model.addAttribute("username", getPrincipal());
return "manager";
}

@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logoutPage(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "home";
}

@RequestMapping(value = "/access_denied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) {
model.addAttribute("username", getPrincipal());
return "accessDenied";
}

private String getPrincipal() {
String userName = null;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
userName = ((UserDetails) principal).getUsername();
} else {
userName = principal.toString();
}
return userName;
}
}

Methods in controller class are trivial. Method getPrincipal is a generic function which returns the logged in user name from Spring SecurityContext. Method logoutPage handles the logging out with a simple call to SecurityContextLogoutHandler().logout(request, response, auth);. It’s handy and saves you from putting cryptic logout logic in your JSP’s which is not really manageable. You might have noticed that ‘/login’ is missing, it is because it will be generated and handled by default by Spring Security.

Adding SpringMVC Configuration Class

org.javajagran.springsecurity.controller.SpringSecurityExampleConfiguration

package org.javajagran.springsecurity.configration;

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;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.javajagran.springsecurity")
public class SpringSecurityExampleConfiguration {

@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");

return viewResolver;
}
}

Adding Initializer class

org.javajagran.springsecurity.configration.SpringMvcInitializer

package org.javajagran.springsecurity.configration;

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

public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

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

@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}

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

}

We can notice that above initializer class extends AbstractAnnotationConfigDispatcherServletInitializer which is the base class for all WebApplicationInitializer implementations. Implementations of WebApplicationInitializer configures ServletContext programmatically, for Servlet 3.0 environments. It means we won’t be using web.xml and we will deploy the app on Servlet 3.0 container.

Adding Views

home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home page</title>
</head>
<body>
<p>Greeting : ${msg}. You developed Spring security example using annotation.</p>
</body>
</html>

admin.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ 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>Admin page</title>
</head>
<body>
<p>Dear <strong>${username}</strong>, Welcome to Admin Page.
<a href="<c:url value="/logout" />">Logout</a>
</p>
</body>
</html>

manager.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ 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>Manager page</title>
</head>
<body>
<p>Dear <strong>${username}</strong>, Welcome to manager Page. 
<a href="<c:url value="/logout" />">Logout</a>
</p>
</body>
</html>

accessDenied.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ 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>Access Denied page</title>
</head>
<body>
<p>Dear <strong>${username}</strong>, You are not authorized to access this page
<a href="<c:url value="/logout" />">Logout</a>
</p>
</body>
</html>

Output screens


Monday, February 27, 2017

Difference between JDK, JRE and JVM.

Hello viewers, Once again welcome back to Java Jagran. Today I am going to discuss "Difference between JDK, JRE and JVM". So Let's start:

JDK

  • JDK is an acronym for Java Development Kit. 
  • It physically exists. 
  • It contains JRE + development tools. 
JDK is also known as Java Development Kit which provides all necessary tools to develop any Java application as well as run it.

JRE

  • JRE is an acronym for Java Runtime Environment. 
  • It is used to provide a runtime environment. 
  • It is the implementation of JVM. 
  • It physically exists. 
  • It contains set of libraries + other files that JVM uses at runtime. 
  • Implementation of JVMs is also actively released by other companies besides Oracle.
Java Runtime Environment provides all necessary libraries and files which is required by JVM to execute any bytecode/.class file. For example: If you want to run any applet on your browser you have to install JRE on your system.

JVM


  • JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides a runtime environment in which java bytecode can be executed.
  • JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because the configuration of each OS differs. But, Java is platform independent.
  • The JVM performs following main tasks:


    • Loads code
    • Verifies code
    • Executes code
    • Provides runtime environment
As a developer, we write a Java program i.e *.java file. Further, we compile the Java program and the *.class file is generated which is also known as bytecode. Now to execute this bytecode we need a something. But what exactly is that? Java Virtual Machine(JVM) is a virtual machine which runs the Java bytecode/.class file and generates the output.

Sunday, February 26, 2017

Features of Java

Hello Readers, Once again welcome back to Java Jagran. Today I am going to discuss features of java. There is given many features of java. They are also known as java buzzwords. Here I am listing some important features of java.
  • Simple
  • Object-Oriented
  • Platform independent
  • Secured
  • Robust
  • Architecture neutral
  • Portable
  • Dynamic
  • Interpreted
  • High Performance
  • Multithreaded
  • Distributed
Now let's discuss each feature in detail.

Simple:

  • The syntax is based on C++ (so easier for programmers to learn it after C++).
  • Removed much confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc.
  • No need to remove referenced objects because there is Automatic Garbage Collection in java.

Object-oriented

  • Object-oriented means we organise our software as a combination of different types of objects that incorporate both data and behaviour.
  • Object-oriented programming(OOPs) is a methodology that simplifies software development and maintenance by providing some rules.
  • Basic concepts of OOPs: Object,Class,Inheritance,Polymorphism,Abstraction,Encapsulation

Platform Independent

  • A platform is the hardware or software environment in which a program runs.
  • There are two types of platforms software-based and hardware-based. Java provides a software-based platform.The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on the top of other hardware-based platforms.
  • It has two components:
    • Runtime Environment
    • API(Application Programming Interface)
  • Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).

Secured

  • Java is secured because: 
    • No explicit pointer: Java Programs run inside virtual machine sandbox
    • Classloader: Adds security by separating the package for the classes of the local file system from those that are imported from network sources.
    • Bytecode Verifier: Checks the code fragments for illegal code that can violate access right to objects.
    • Security Manager: determines what resources a class can access such as reading and writing to the local disksecurities
  • These are provided by java language. Some security can also be provided by application developer through SSL, JAAS, Cryptography etc.

Robust

  • Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security problem. There is automatic garbage collection in java.
  • There is exception handling and type checking mechanism in java.

Architecture-neutral

  • There is no implementation dependent features e.g. size of primitive types is fixed.
  • In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures.

Portable

  • We may carry the java bytecode to any platform.

High-performance

  • Java is faster than traditional interpretation since byte code is “close” to native code still somewhat slower than a compiled language (e.g., C++)

Distributed

  • We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet.

Multi-threaded

  • A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn’t occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications etc.

Wednesday, December 21, 2016

Importance of Collection framework in java.

Hello Readers, Once again welcome back to Java Jagran. Today i am going to talk about Collection framework in java. You people might be heard from others that collection framework is very important topic in java. Yes, it's a very important topic with respect to interview, with respect to exams and most important with respect to work. There is no java project in this world without using Collection framework.
Now, the question is why Collection framework is important? Take an real time project example. For example you are working on a EMS(Employee Management System). In that you have one page for search employees. So for that you have to carry group of employee objects from one layer of application to another layer(DAO layer to Service layer, Service layer to presentation layer). So we can't take multiple objects from one class to another class, one method to another method. For that we need some wrapper in which we can put all the employee objects and send from one place to another place. Same what collection doing. Collection framework doing the work of wrapper or you can say like a bag. We can put all the employee object inside Collection object and send from one layer of application to another layer of application.
Some people used to say that we can use array also for the same. But there is too many benefits of using collection over array. The main problems with arrays is:
  • Array is fix in size( We have to decide the size before creating array) 
  • It's very hard to do CURD(Create-Insert, Update, Retrieve, Delete-Remove) operations on array.
  • We can't store heterogeneous object in array.

 We are getting so many pre-defined operations in the form of methods. For example we have to search an item in array, we have to write lot of code for that(We have to implement one of the searching algorithm). But with the collection it's too simple. All the collection classes provided one or other methods for searching an item from the collection. Same for the adding, removing, updating etc.

The next question is why collection is called framework? You people might be heard that Spring, Hibernate, Struts etc are frameworks. But how and why collection? For that first we have to understand the concept of framework. When we can call framework and when we call technology. Framework is almost ready thinks. I means to say that whatever logic is common for all the application that that is provided by a framework. And we have to write only business specific logic for building applications. Collections also providing the same. In the case of collections also same. Actually collection is the well implemented DS(Data Structures). In C language and some other languages we have to write the code by our self. But Java people provided a classes for all the DS and that is given a name as Collection. So we no need to write code for that, we can directly use those classes. That's why Collection is called framework. That's all for now. Hope you people will get benefited by this. For more information keep reading Java Jagran.
You can also get so many thinks related to java at bellow given YouTube and Facebook:



Tuesday, May 24, 2016

Why main method should be public static void main(String[] args) in java?

Hello friends, Once again welcome back to Java Jagran. today i am here with "Why main method should be public static void main(String[] args) in java?" We all know that thsi is the signature/prototype of main method, but the question is why this? And the reason is here:
For understanding this we have to first understand little bit about JVM. First we have to understand how JVM calls main method of our class? When ever we are starting JVM by calling:
                          cmd> java MyClass arg1 arg2 ...       
This "java" program is nothing but our JVM. So it will collect all the three arguments( MyClass, args1, args2 ...). Then after it will create one String array and stores arg1, arg2 ... in that array. Then it will calls main() method on our class by passing that String array. Now lets understand each and every key of main method.
  • public: It must be public because if we take it as private then it must be only called from inside that class, if we take it as default then it must be only called from inside that class or same package, if we take it as protected then it must be only called from same class, same package, child classes of other package also. But JVM class is the other class that is not available in same package and also not a child class of our class. So it must be public.
  • static: It must be static because JVM is not creating object of our class for calling main method. The reason why JVM use not to create object of our class is: If our class have constructors then how JVM will identify that which constructor they have to use for creating object. And if it is parametrized then what data they have to pass in parameter. For solving these problems only sun people given it as static.

  • void: It must be void because main method is called by JVM. And if it is having some return value then what JVM will do with that data. It's a useless. That why sun people kept it as void.
  • main(): It's name must me main because if this is not specified then how JVM will know which method they have to call. That why sun people written code in JVM that will call only method with name "main".
  • String[]: As I already said, JVM use to collect all arguments and create one String array and then pass it to main method. The reason they taken it as String[] only is: In String we can store any type of data. For example if they taken it as int then how can we pass float/double and String value, If they taken it as float/double then how can we pass String, boolean etc data. But in String we can pass any type of data like int, float, boolean, String etc.

Now lets understand how  JVM calling main method: When ever we are stating JVM by calling  
                             java MyClass arg1 arg2 ...
Then JVM do like this:
                             MyClass.main(new String[]{arg1, arg2, ...});


Now lets see possible prototype of main method:
  • public static void main(String []args) 
  • static public void main(String []args)
  • public static void main(String ...args)
  • public final synchronized strictfp static void main(String[] params)