Milos Zikic - Personal site, sharing thoughts about startups, products and engineering

Grails easy REST Security

REST services did not came with a standard way of authentication like WS-Security for SOAP services. You can always turn to OAuth authentication which is great if you are providing services for 3rd parties that will utilize your user base and their data (e.g. Facebook or Twitter) but it is not that easy to integrate and it may come as an overhead if you are sharing your services with control set of clients (e.g. other businesses that will consume your services from their servers). 

Since we are talking here about mostly "controlled" environment then all the complexity can be avoided by simply using SSL and just sending client identification to know who is consuming your data. This is the approach that many are taking and simple adding an "apiKey" parameter at the end, e.g.


https://awesomeapi.api/hotels/?apiKey=

This is fine and will provide enough security, but if you are using simple apiKeys (e.g. like client name or some username) it can be easy to guess the api key and use your service as someone else (especially if you have your service documentation publicly). Easy solution is to use hash based apiKeys which are not guessable. More secure way is to add additional argument something like "password". This way it would be very hard to guess both parameters and breach your service. E.g. this can be easily achieved by adding spring-security-plugin, adding a special role for the API consumers and generate accounts for the clients.

This is perfectly good approach and you get all the power of spring security. However if you find spring security filters as an overhead to your API or want to separate regular users and api users this might not be great option. Another benefit is to have a clean separation of your APIKeys and keep track who is owning them. And if they become compromised add ability to generate new APIKeys for the same user account.

Grails filters make it very easy to support this. Just create a file called something like APIFilters.groovy in your grails-app/conf folder and add code like this:



class ApiFilters {

def filters = {
all(uri: '/**') {

def renderError = { status, message ->
boolean xml = request.getHeader("accept").contains("xml")
boolean json = request.getHeader("accept").contains("json")
if (json || !xml) {
render(status: status, contentType: 'application/json', text: '{"error":"' + message + '"}')
} else {
render(status: status, contentType: 'application/xml', text: '' + message + '')
}
return false
}
before = {
try {

String authorizationHeader = request.getHeader('authorization')?.trim()?.toLowerCase()

String key

if (authorizationHeader == null) {
// Try with api_key request parameter and render error if it's missing.
key = params.api_key
if (key == null) {
renderError(403, 'I need an authorization parameters to serve this request.')
return false
}
} else {
try {
byte[] token
if (authorizationHeader.startsWith("apikey ")) {
token = authorizationHeader.substring(7).getBytes("UTF-8");
}
key = new String(token, "UTF-8");
} catch (ignore) {
}
// Return if key is empty.
if (key == null || key.trim() == "") {
renderError(401, "Check your authorization header syntax. It should look like \"Authorization: APIKey [your_api_key]\".")
return false
}
}
// Find API key and return if it does not exist.
APIKey apiKey = APIKey.findByApiKey(key)
if (apiKey == null) {
renderError(401, 'Unknown API key.')
return false
}
} catch (Exception e) {
renderError(500, 'Darn it, please try later!')
}

}

}
}
}


And create APIKey domain object to hold your API Keys. API Keys should be some randomly generated hash so they are not guessable.

And voila, you have a perfectly secured grails REST service. Rest clients just need to pass their api keys as a parameter or in the header of the request like this:


Authorization: APIKey [your_api_key]

If for some reason you want to allow http access to your API there is now a common way to solve this by signing your message based on a shared secret between the client and the service. This is called HMAC (Hash-based Message Authentication Code). This is the approach many companies have taken like Amazon and Microsoft. This approach follows the 2-legged OAuth (keep in mind that OAuth is authorization specification and not authentication). As it adds additional complexity with calculating the hash I would always recommend going SSL only and have the API access as simple as possible (developers love simple!).

Share this post

comments powered by Disqus