Spring Security 4 - HTTP basic authentication example

Posted on October 7, 2017


Technologies used:  Spring Security 4.2.3.RELEASE | Spring MVC 4.3.10.RELEASE | Java SE 1.8 | Maven 3.3.9 | Eclipse Neon.3 | Apache Tomcat 7.0.47

What is the HTTP basic authentication? It is a simple challenge and response mechanism used by a server to challenge a client request. In HTTP basic authentication, client’s username and password are concatenated, base64 encoded and passed to server in Authorization HTTP header as follows.

spring-security-http-auth.png

In our previous post Spring Security 4 - Hello World example, we have learned about the form-based authentication using the HttpSecurity.formLogin() method, which generates a login page asking for username and password. In this post, I will show you how to set up the HTTP basic authentication in Spring MVC application with Spring security.

Project structure

Review the following web project structure build using Maven build tool.

spring-security-http-auth-01.png

You can refer this article to learn - How to create a web project using maven build tool in eclipse IDE.

Jar dependencies

Edit pom.xml file of your maven project and add the following dependencies in it.

<dependencies>
  <!-- Spring MVC Dependency -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.10.RELEASE</version>
  </dependency>
  <!-- Spring Security Dependency -->
  <dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
    <version>4.2.3.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>4.2.3.RELEASE</version>
  </dependency>
  <!-- Servlet Dependency -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
  </dependency>
  <!-- JSP Dependency -->
  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.1</version>
    <scope>provided</scope>
  </dependency>
</dependencies>

Controller class

Create a simple @Controller class under com.boraji.tutorial.spring.controller package as follows. 

MyController.java

package com.boraji.tutorial.spring.controller;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {

   @GetMapping("/")
   public String index(Model model) {

      // Get authenticated user name from SecurityContext
      SecurityContext context = SecurityContextHolder.getContext();
      
      model.addAttribute("message", "You are logged in as " 
                     + context.getAuthentication().getName());
      return "index";
   }
}

JSP views

Create an index.jsp file under src\main\webapp\WEB-INF\views folder and write the following code in it.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>BORAJI.COM</title>
</head>
<body>
  <h2>Spring Security 4 - HTTP basic authentication example</h2>
  <hr />
  <h4>${message}</h4>
</body>
</html>

 

Spring security configuration class

To enable HTTP base authentication with spring security, you can use the HttpSecurity.httpBasic() methods in your @Configuration class. 

Create a @Configuration class by extending the WebSecurityConfigurerAdapter class as follows.

WebSecurityConfig.java

package com.boraji.tutorial.security.config;

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;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.inMemoryAuthentication()
      .withUser("admin").password("admin123").roles("USER");
   }

   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests().antMatchers("/").hasRole("USER")
      .and()
      .httpBasic();
   }
}

This Java configuration class creates a Servlet Filter known as the springSecurityFilterChain, which is responsible for all security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc) within your application.

The overridden method configure(AuthenticationManagerBuilder auth) configure the in memory authentication with user credentials and roles. You can configure the other authentications too such as JDBC, LDAP etc.

The overridden method configure(HttpSecurity http) configure the web based security for all HTTP request. By default it will be applied to all requests, but can be restricted using the requestMatcher() or other similar methods.

From the above configuration class, it is clear that, URL '/'  is secured and only accessible by users who have the role 'USER'

Registering springSecurityFilterChain Filter

In Java configuration, you can register the spring springSecurityFilterChain using the base class AbstractSecurityWebApplicationInitializer as follows.

SecurityWebApplicationInitializer.java

package com.boraji.tutorial.security.config;

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

public class SecurityWebApplicationInitializer 
      extends AbstractSecurityWebApplicationInitializer {

}

This configuration only registers the springSecurityFilterChain Filter for every URL in your application.

Spring web configuration class

Create a web @Configuration class annotated with @EnableWebMvc and @ComponentScan as follows.

WebConfig.java

package com.boraji.tutorial.security.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.boraji.tutorial.spring.controller" })
public class WebConfig extends WebMvcConfigurerAdapter {
   @Override
   public void configureViewResolvers(ViewResolverRegistry registry) {
      registry.jsp().prefix("/WEB-INF/views/").suffix(".jsp");
   }
}

Application initializer class

Create a MvcWebApplicationInitializer class, which will replace our traditional web.xml, to initialize the Servlet container.

Load the WebSecurityConfig and WebConfig classes using the getRootConfigClasses() and getServletConfigClasses() methods as follows.

MvcWebApplicationInitializer.java

package com.boraji.tutorial.security.config;

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

public class MvcWebApplicationInitializer 
         extends AbstractAnnotationConfigDispatcherServletInitializer {

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

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

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

 

Build + Deploy + Run application

Use the following maven commands to build, deploy and run Tomcat server.

mvn clean install  (This command triggers war packaging)

mvn tomcat7:run (This command run embedded tomcat and deploy war file automatically)

You can refer this link to learn how to run the above commands in Eclipse IDE.

 

Enter the http://localhost:8080/ URL in browser's address bar to test the HTTP basic authentication configuration.

On entering the URL, you will see the dialog box asking for username and password as follows.

spring-security-http-auth-02.png

On successful login, you will see the index page as follows.

spring-security-http-auth-03.png