Saturday, February 16, 2013

Spring Security and Http Basic Authentication

This article will show you how to use Spring Security to protect your web application with Http Basic Authentication.

Our application will require that users will authenticate themeselves with Http Basic Authentication. Unauthorized users will get 401 UNAUTHORIZED response and will have to authenticate themselves with login and password.

I expect that your application is already using Spring Framework and Maven. So, to start using Spring Security we need to add these maven dependencies:


We need to add Spring Security Filter to web.xml configuration so that it will intercept all HTTP requests.



Then we need to implement a UserService that checks that the user exists (e.g. in a database).

public class UserServiceImpl implements UserService {

   private Map<String, UserDetails> users = new HashMap<String, UserDetails>();

   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

      if (users.containsKey(username)) {
         return users.get(username);

      throw new UsernameNotFoundException("User " + username + " not found");

The next step is to implement a BasicAuthenticationEntryPoint that would tell users that they have to authenticate in order to access this application.

public class VozisBasicAuthenticationEntryPoint extends 
BasicAuthenticationEntryPoint {

public void commence(HttpServletRequest request, HttpServletResponse response, 
AuthenticationException authException) throws IOException, ServletException {
      response.addHeader("WWW-Authenticate", "Basic realm=\"" + 
         getRealmName() + "\"");
      PrintWriter writer = response.getWriter();
      writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + 
         " - " + authException.getMessage());

Now we have all components that we need, let's integrate them together. Below is the example of security.xml configuration:

<beans:beans xmlns=""
   xsi:schemaLocation=" ">

   <global-method-security secured-annotations="enabled" />

   <http auto-config="false" create-session="stateless">
      <http-basic entry-point-ref="authenticationEntryPoint" />

   <beans:bean id="authenticationEntryPoint"
      <beans:property name="realmName" value="Vozis" />

   <authentication-manager alias="authenticationManager">
      <authentication-provider user-service-ref="userService" />

   <beans:bean id="userService" class="" />


  1. This comment has been removed by the author.

  2. Thank you for this super helpful post. We still need to configure web.xml to register security.xml file. Is that correct?

    Something like: