跳至主要内容

Create a restful application with AngularJS and Grails(2): Secure the backend REST API


Secure the backend REST API

In Spring application, Spring Security is usually used to secure the application. Grails has a builtin Spring Security based plugin to integrate Spring Security into Grails applications.

Install SpringSecurity core plugin

Open BuildConfig.groovy file, add spring-security-core plugin.
plugins {
 ...
 compile ":spring-security-core:2.0-RC2"
}
Run the following command in the project root folder to initialize the spring security plugin.
grails compile --non-interactive --refresh-dependencies
And use the built-in s2-quickstart script from this plugin to create the essential domain classes.
grails s2-quickstart Person Authority Requestmap
When it is done, the basic security configuration is added in Config.groovy.
grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.hantsylabs.grails.example.security.Person'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.hantsylabs.grails.example.security.PersonAuthority'
grails.plugin.springsecurity.authority.className = 'com.hantsylabs.grails.example.security.Authority'
grails.plugin.springsecurity.requestMap.className = 'com.hantsylabs.grails.example.security.Requestmap'
grails.plugin.springsecurity.securityConfigType = 'Annotation'
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
 '/':                              ['permitAll'],
 '/index':                         ['permitAll'],
 '/index.gsp':                     ['permitAll'],
 '/**/js/**':                      ['permitAll'],
 '/**/css/**':                     ['permitAll'],
 '/**/images/**':                  ['permitAll'],
 '/**/favicon.ico':                ['permitAll']
 ]

Configure securityConfigType

There are three securityConfigType supported by this spring security plugin.
  • Annotation
  • InterceptUrlMap
  • Requestmap
By default, the Annotation type is configured.
grails.plugin.springsecurity.controllerAnnotations.staticRules is use for configuring the protection rule for the static resources. It is a map, the key is the url, the value is the configuration attribute which is a list and can accept the Spring security constants or Spring expression, eg. IS_AUTHENTICATED, isFullyAuthenticated(). If you have some experience of Spring security before, it is easy to understatnd.
Besides these, in your Java codes, you can use Grails or Spring Security specific @Securedannotation on methods in a Controller to apply the security restrict rules.
If you select InterceptUrlMap, all resources are protected by url intercepting only.
grails.plugin.springsecurity.securityConfigType = 'InterceptUrlMap'
grails.plugin.springsecurity.interceptUrlMap  = [
 '/':                              ['permitAll'],
 '/index':                         ['permitAll'],
 '/index.gsp':                     ['permitAll'],
 '/**/js/**':                      ['permitAll'],
 '/**/css/**':                     ['permitAll'],
 '/**/images/**':                  ['permitAll'],
 '/**/favicon.ico':                ['permitAll']
 ]
For Requestmap, it is easy to understand, it store the url intercepting mapping rules into database.
grails.plugin.springsecurity.securityConfigType = 'Requestmap'
There is a Requestmap class already generated for this project.
class Requestmap {

 String url
 String configAttribute
 HttpMethod httpMethod

 static mapping = {
  cache true
 }

 static constraints = {
  url blank: false, unique: 'httpMethod'
  configAttribute blank: false
  httpMethod nullable: true
 }
}
In the BootStrap.groovy class, you can add some codes to initialize the Requestmap.
def init = { servletContext ->
 ...
  for (String url in [
   '/', '/index', '/index.gsp', '/**/favicon.ico',
   '/**/js/**', '/**/css/**', '/**/images/**',
   '/login', '/login.*', '/login/*',
   '/logout', '/logout.*', '/logout/*']) {
   new Requestmap(url: url, configAttribute: 'permitAll').save()
   }

}
In this sample, InterceptUrlMap is used as example.
grails.plugin.springsecurity.securityConfigType = 'InterceptUrlMap'
grails.plugin.springsecurity.interceptUrlMap  = [
 '/':                              ['permitAll'],
 '/index':                         ['permitAll'],
 '/index.gsp':                     ['permitAll'],
 '/**/js/**':                      ['permitAll'],
 '/**/css/**':                     ['permitAll'],
 '/**/images/**':                  ['permitAll'],
 '/**/favicon.ico':                ['permitAll'],
 '/login/**':                 ['permitAll'],
 '/logout/**':                 ['permitAll'],
 '/**':      ['isFullyAuthenticated()']
 ]
The security plugin provides a LoginController and LogoutController for login and logout actions.

Run the project

Open BootStrap.groovy file, add some sample user data for test purpose.
def init = { servletContext ->
  
 def person =new Person(username:"test", password:"test123")
 person.save()
  
 def roleUser=new Authority(authority:"ROLE_USER")
 roleUser.save()
  
 new PersonAuthority(person:person, authority:roleUser).save()
}
In Eclipse IDE(Spring ToolSuite), select Run as-> Grails Command(run-app) in the project context menu,
Or in the command line, run the following command in the project root folder to run the this project.
grails run-app
Try to access the protected REST API resources, for example,http://localhost:8080/angluarjs-grails-sample/books.json. It will redirect to a login page. Login as test/test123, it will show the protected resources.

Sample codes

评论

此博客中的热门博文

AngularJS CakePHP Sample codes

Introduction This sample is a Blog application which has the same features with the official CakePHP Blog tutorial, the difference is AngularJS was used as frontend solution, and CakePHP was only use for building backend RESR API. Technologies AngularJS   is a popular JS framework in these days, brought by Google. In this example application, AngularJS and Bootstrap are used to implement the frontend pages. CakePHP   is one of the most popular PHP frameworks in the world. CakePHP is used as the backend REST API producer. MySQL   is used as the database in this sample application. A PHP runtime environment is also required, I was using   WAMP   under Windows system. Post links I assume you have some experience of PHP and CakePHP before, and know well about Apache server. Else you could read the official PHP introduction( php.net ) and browse the official CakePHP Blog tutorial to have basic knowledge about CakePHP. In these posts, I tried to follow the steps describ

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to add   hibernate-envers   as project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple   @Audited   annotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If   @Audited   annotation is placed on a property, this property can be tracked. @Entity @Audited public class Signup implements Serializa