Creating RESTful API’s
with Grails and Spring
Security
Álvaro Sánchez-Mariscal
Web Architect – odobo
!
@alvaro_sanchez
About me
• Passionate software developer.
• Founded Salenda in 2005.
• Co-founded Escuela de Groovy in 2009.
• Groovy/Grails lover since 2007.
• Working now at Odobo as Web Architect.
• HTML5 games platform for:
• Game developers.
• Casinos.
• Check out https://play.odobo.com and try
for free!
Different approaches
• Using just @Resource.
• With uri attribute.
• With explicit UrlMappings.
Demo
step1 … step2
Different approaches
• Creating explicitly a controller and
extending RestfulController.
• Defining just the constructor.
• Implementing actions based on the URL
mappings report.
Demo
step3 … step4
Different approaches
• Scaffolding (but don’t tell your mother).
Customizing response
• Customize default renderers.
• Register custom marshallers.
• Use Hypermedia (and fasten your seat
belts!).
• Use Dan Wood’s rest-renderers plugin.
Demo
step5 … step7
Adding Spring Security
Motivation: we need to break down the
traditional, monolithic Grails applications, in
2 different apps:
1. A pure HTML5/Javascript frontend.
2. A mere RESTful Grails backend.
Adding Spring Security
Issue: The existing Spring Security plugins
would not work with a RESTful, browser-
based client.
REST is much
more than just
returning JSON.
RESTful is about*
Client / server.
Stateless.
Cacheable.
Layered.
* Source: Wikipedia.
Meet Spring Security REST
A stateless, token-based
authentication for your
RESTful API’s
Authentication
Demo
Invoking a protected
resource
Demo
Authentication Endpoint
• Uses the default
authenticationManager bean,
which in turn uses all the registered
authentication providers.
• Receives username and password, and
generates a customizable JSON
response.
Authentication Endpoint
• Credentials can be extracted from:
1. Request parameters.
2. A JSON payload.
3. Any custom implementation
Token Generation
• 2 strategies out-of-the-box:
1. Using java.security.SecureRandom
(default).
2. Using java.util.UUID.
• A custom implementation can be
plugged.
Token Storage
• In Memcached (default).
• Using GORM.
• Write your own.
Token Storage
Token Validation
• If the token header (X-Auth-Token by
default) is present, the request will be
validated.
• Otherwise, the plugin won’t participate in
the filter chain.
Token Validation
• If the passed token exists on the token
storage, the principal will be stored on
the security context.
• It can be retrieved using
springSecurityService.principal
CORS support
• Grails doesn’t support CORS (vote for
GRAILS-10914).
• This plugin comes prepackaged with cors
plugin.
Demo
OAuth support
OAuth support
Demo
DevQA: make
your testers
happier with
Groovy, Spock
and Geb
Tomorrow,
17:15
Thanks!
Álvaro Sánchez-Mariscal
Web Architect – odobooo
!
@alvaro_sanchez
alvarosanchez

Creating RESTful API’s with Grails and Spring Security