跳至主要内容

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

发表评论

此博客中的热门博文

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 thePostentity 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 converter In this example…

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 addhibernate-enversas 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@Auditedannotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If@Auditedannotation is placed on a property, this property can be tracked.

Spring Data Mongo: bridge MongoDB and Spring

Spring Data Mongo: bridge MongoDB and SpringMongoDBis one of the most popular NoSQL products, Spring Data Mongo(Maven archetype id is spring-data-mongodb) tries to provides a simple approach to access MongoDB. Configuration Add the following code fragments in your Spring configuration. <!-- Mongo config --> <mongo:db-factory id="mongoDbFactory" host="localhost" port="27017" dbname="conference-db" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoDbFactory" /> </bean> <mongo:repositories base-package="com.hantsylabs.example.spring.mongo" /> Firstly, declare aDbFactorywhich is responsible for connecting to the MongoDB server. Then, register theMongoTemplateobject which envelop the data operations on MongoDB. Lastly addmongo:repositorieswith an essentialbase-packageattribute, Spring will discovery your d…