Securing REST APIs or Web Application With Basic Authentication

If you implement REST Web Services, you want to secure them. The simplest approach is to use the basic authentication () with user name and password. To protect all the resources behind the REST APIs, you can simply implement filter as introduced in Java Servlet 2.3 ().

As I searched the Internet, I could not find an out of box filter implementation. After spending a bit time on it, I got a simple filter work as listed below. Although designed to protect REST APIs, it can actually work with any Web application (REST API service is essentially a Web application that returns XML or JSON content instead of HTML).

Lost VMs or Containers? Too Many Consoles? Too Slow GUI? Time to learn how to "Google" and manage your VMware and clouds in a fast and secure HTML5 App.

The sample just checks the user name and password as hardcoded. In real project, you want to check the combination with database, SSO, or simply file. Whatever the source of the credential, it’s important to validate the user, and get her role which can be deferred later to other parts as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package org.doublecloud.rest.demo;
 
import java.io.IOException;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
 
@WebFilter("/*")
public class BasicAuthFilter implements Filter
{
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
  {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
 
    try
    {
      String authHeader = req.getHeader("Authorization");
      String encodedCred = authHeader.substring(6); // after the "Basic "
 
      byte[] plainCred = DatatypeConverter.parseBase64Binary(encodedCred);
      String userPass = new String(plainCred);
 
      int pos = userPass.indexOf(":");
      String user = userPass.substring(0, pos);
      String password = userPass.substring(pos + 1);
 
      if("admin".equals(user) && "doublecloud".equals(password))
      {
        req.setAttribute("user", user);
        chain.doFilter(req, res); // pass the request along the filter chain
      }
      else
      {
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      }
    }
    catch(NullPointerException npe)
    {
      res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    catch(Exception e)
    {
      res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
 
  public void init(FilterConfig fConfig) throws ServletException
  {}
 
  public void destroy()
  {}
}
This entry was posted in Software Development and tagged , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  • NEED HELP?


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.