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.


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.


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.

  <!-- Spring MVC Dependency -->
  <!-- Spring Security Dependency -->
  <!-- Servlet Dependency -->
  <!-- JSP Dependency -->

Controller class

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


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;

public class MyController {

   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.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html >
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <h2>Spring Security 4 - HTTP basic authentication example</h2>
  <hr />


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.


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;

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

   protected void configure(AuthenticationManagerBuilder auth) throws Exception {

   protected void configure(HttpSecurity http) throws Exception {

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.


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.


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;

@ComponentScan(basePackages = { "com.boraji.tutorial.spring.controller" })
public class WebConfig extends WebMvcConfigurerAdapter {
   public void configureViewResolvers(ViewResolverRegistry registry) {

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.


package com.boraji.tutorial.security.config;

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

public class MvcWebApplicationInitializer 
         extends AbstractAnnotationConfigDispatcherServletInitializer {

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

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

   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.


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