{{announcement.body}}
{{announcement.title}}

Grails Security: Grails 3.3 With Spring Security Core and Spring Security Rest Plugin

DZone 's Guide to

Grails Security: Grails 3.3 With Spring Security Core and Spring Security Rest Plugin

Better authenticate users for your application with Grails 3.3 and Spring Security Core and Rest plugin.

· Security Zone ·
Free Resource

The Spring security core plugin allows users to create a structure for Grails application authentication. The Spring security rest plugin allows you to use resources in a REST-like manner.

The first thing that you have to do is add these two dependencies to your build.gradle file.

compile ‘org.grails.plugins:spring-security-core:3.2.0’
compile ‘org.grails.plugins:spring-security-rest:2.0.0.M2’


Run the command to generate the auth structure.

grails s2-quickstart com.lucasaquiles.auth User Role


The command generated the domain classes, User, Role, UserRole, and UserPasswordEncoderListener, in order to create a strategy for password generation and application.yml to configurations.

Now, you need to map your authenticated URLs and allow the browser to read asset contents with non-authenticated users.

grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.lucasaquiles.auth.User'
  grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.lucasaquiles.auth.UserRole'
  grails.plugin.springsecurity.authority.className = 'com.lucasaquiles.auth.Role'
  grails.plugin.springsecurity.controllerAnnotations.staticRules = [[pattern: '/',               access: ['permitAll']], 
                                                                    [pattern: '/error',          access: ['permitAll']], 
                                                                    [pattern: '/index',          access: ['permitAll']], 
                                                                    [pattern: '/index.gsp',      access: ['permitAll']], 
                                                                    [pattern: '/shutdown',       access: ['permitAll']], 
                                                                    [pattern: '/assets/**',      access: ['permitAll']], 
                                                                    [pattern: '/**/js/**',       access: ['permitAll']], 
                                                                    [pattern: '/**/css/**',      access: ['permitAll']], 
                                                                    [pattern: '/**/images/**',   access: ['permitAll']], 
                                                                    [pattern: '/**/favicon.ico', access: ['permitAll']]
                                                                   ]


grails.plugin.springsecurity.filterChain.chainMap = [[pattern: '/assets/**', filters: 'none'], 
                                                     [pattern: '/**/js/**',       filters: 'none'], 
                                                     [pattern: '/**/css/**',      filters: 'none'], 
                                                     [pattern: '/**/images/**',   filters: 'none'], 
                                                     [pattern: '/**/favicon.ico', filters: 'none'], 
                                                     [pattern: '/**',             filters: 'JOINED_FILTERS']
                                                     ]


The postOnly grants just POST HTTP request to logout.

The staticRulesmaps the URL to the resource path, setting the pattern and access. The rule [‘permitAll’] grants unauthenticated users to read files without logging in on the application. If you run your app without that, your application will not display the Grails default design.

Modify your application.ymlfile by adding the following code: 

plugin:
        springsecurity:
            controllerAnnotations:
                chainMap:
                    '/api/**': 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter'
                    '/**': 'JOINED_FILTERS,-restTokenValidationFilter,-restExceptionTranslationFilter'
            rest:
                logout:
                    endpointUrl: '/api/logout'
                token:
                    validation: 
                        useBearerToken: false
                        headerName: 'X-Auth-Token'


The chainMap defines filters to be applied to /api/** and /** URL.

The rest property defines the auth settings and URL paths to pattern /api/.

Let’s creates a new user and manually test the authentication via API. Add the following code on the init block in Boostrap.groovy.

def roleAdmin = new Role(authority: 'ROLE_ADMIN').save()
def adminUser = new User(username: 'user', password: 'user').save()


UserRole.create adminUser, roleAdmin         
UserRole.withSession {     it.flush()     it.clear()}


Run the grails app.

grails run-app


Testing the API

curl -H "Content-Type: application/json" -H "Accept: application/json" -d '{"username":"user","password":"user"}' http://localhost:8080/api/login


Result:

{  
   "username":"user",
   "roles":[  
      "ROLE_ADMIN"
   ],
   "access_token":"eyJhbGciOiJIUzI1NiJ9.eyJwcmluY2lwYWwiOiJINHNJQUFBQUFBQUFBSlZTdlVcL2JRQlJcL1RvTkFSV29CcVVnTXNFQzN5cEhvbUlsdlVia0JOV1NoRXVoaVA4ekIrYzY5TzBPeVZKbmFnWUdLRDZsUzE0NzhKN0R3QjFSbFlHVm01WjBoT0dWQnZjbCs5XC9QdjZcL25zQnZxTWh2ZXhabHdZUHhWWnpLVnZVczFsYkRETU5MZHRQek9vSTdRNVlpa0hObWdDOThjcmdSZEFpVWNXUm9JZHRzY3Fnc200c3RMY3dkQldXeHFtbFk0ZkdMYzBTM0JmNlYzXC9rVHRVR3Y4UktLaTkzeVhvWDRkaEZvWXFrN2FtNUVJcjVScWpkUmdxWm9FS2Q5M29UVWczS0Mxbnd2UkMrMUd5cHNBb2dFR1cyVzFGcWh5TmhkZjNaalBMUmFXT3RockFRTXFNSVhkUGt0U3RzKzd1blUxSkNiN0FWeWkzVW84T2RmZldRWDNINDg4cElTZzFWOUpNTldTaUlyN0ZuVGp4ZDhhUExnOVwvZFJvbEFPcmszZlBmRlBPeFdlaWNiOXhPNUVWN29ZWFJIdXNGck5wS3ljMXd3YnltMFNuXC8rYmw2ZkhyelwvZk1MVW5hSXhmXC9meDlUTVEzUHRPWldrVERPcmVuWkV0UHRsOTB6a3M4K1RkN2ZROXVzOFNRWFNIeVV0Um84U0JUSEZMV3NsdW4xYmVQbHBKVmpZbkpuXC91Rnh6cjJYbmswUmY1Wm5kc3Z4QTBhb09ybjljSEU3K0pZSVAwTGZIUklaVStWQUJxbVZKRVwvVzNzOVB4d1pPcmd6eEE5MmUrQTJkVzdRNFFBd0FBIiwic3ViIjoidXNlciIsInJvbGVzIjpbIlJPTEVfQURNSU4iXSwiZXhwIjoxNTMwMTE5MTQ1LCJpYXQiOjE1MzAxMTU1NDV9.Q5JHbjUJoZ1wCrF8fkB7aYb5wjFqCd7rMN-RPRGzock"
}


If the user was authorized, you can call methods from the springSecurityService to identify the user in your controllers.

Topics:
grails 3 ,groovy ,spring-security ,security ,tutorial ,spring ,security core ,rest security plugin

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}