Securing REST API using custom tokens (stateless, no UI, no cookies, no basic authentication, no OAuth, no login page)

Karthik Karuppannan picture Karthik Karuppannan · Aug 14, 2014 · Viewed 30.8k times · Source

There are lots of guidelines, sample codes that show how to secure REST API with Spring Security, but most of them assume a web client and talk about login page, redirection, using cookie, etc. May be even a simple filter that checks for the custom token in HTTP header might be enough. How do I implement security for below requirements? Is there any gist/github project doing the same? My knowledge in spring security is limited, so if there is a simpler way to implement this with spring security, please let me know.

  • REST API served by stateless backend over HTTPS
  • client could be web app, mobile app, any SPA style app, third-party APIs
  • no Basic Auth, no cookies, no UI (no JSP/HTML/static-resources), no redirections, no OAuth provider.
  • custom token set on HTTPS headers
  • The token validation done against external store (like MemCached/Redis/ or even any RDBMS)
  • All APIs need to be authenticated except for selected paths (like /login, /signup, /public, etc..)

I use Springboot, spring security, etc.. prefer a solution with Java config (no XML)

Answer

manish picture manish · Aug 15, 2014

My sample app does exactly this - securing REST endpoints using Spring Security in a stateless scenario. Individual REST calls are authenticated using an HTTP header. Authentication information is stored on the server side in an in-memory cache and provides the same semantics as those offered by the HTTP session in a typical web application. The app uses the full Spring Security infrastructure with very minimum custom code. No bare filters, no code outside of the Spring Security infrastructure.

The basic idea is to implement the following four Spring Security components:

  1. org.springframework.security.web.AuthenticationEntryPoint to trap REST calls requiring authentication but missing the required authentication token and thereby deny the requests.
  2. org.springframework.security.core.Authentication to hold the authentication information required for the REST API.
  3. org.springframework.security.authentication.AuthenticationProvider to perform the actual authentication (against a database, an LDAP server, a web service, etc.).
  4. org.springframework.security.web.context.SecurityContextRepository to hold the authentication token in between HTTP requests. In the sample, the implementation saves the token in an EHCACHE instance.

The sample uses XML configuration but you can easily come up with the equivalent Java config.