Monday, October 5, 2015

Grails Security Core and Security UI Walk thru

Getting started with Grails Spring Security Core and Spring Security UI    


These are two separate plug-ins with volumes of somewhat readable documentation here and here. See this YouTube video that provides a walk-thru using below syntax.

First things first: Start a new project

Installing Security Core:

1)     Open conf > BuildConfig.groovy
2)     Add      compile ":spring-security-core:2.0-RC5"    to the plugins area
3)     Refresh dependencies by ALT+G R  //this installs  the security core
4)     Open the command history
Type:        s2-quickstart com.domain.auth User Role     
                      
                  At this point you have Role, User, and UserRole domain classes

Configuring Security Core:

1)     Go to the bottom of config.groovy, you should see some configuration lines for spring security. This is where we define which roles have access to specific pages. We will get into roles in the Configuring Spring Security UI section.

2)     Add the following above staticRules:      
grails.plugin.springsecurity.logout.postOnly = false// allows logout to work
3)     Add the following to your staticRules:
                                     '/dbconsole/**':  ['ROLE_ADMIN'],
         '/plugins/**':     ['ROLE_USER']

4)  Open bootstrap.groovy and do this:

import com.domain.auth.*
class BootStrap {
      def init = { servletContext ->
            def adminRole = Role.findOrSaveWhere(authority:'ROLE_ADMIN')
            def user = User.findOrSaveWhere(username:'admin',password:'password')

            if(!user.authorities.contains(adminRole)){
                  UserRole.create(user,adminRole,true)
            }
}
      def destroy = {
      }
}


Installing Spring Security UI:

1)     Open conf > BuildConfig.groovy
2)     Add      compile ":spring-security-ui:1.0-RC2"      to the plugins area
3)     Refresh dependencies by ALT+G R  //this installs  the security UI


Configuring Spring Security UI

1)     Open config.grooy and add additional configuration to staticRules

'/user/**':     ['ROLE_ADMIN'],
'/role/**':     ['ROLE_ADMIN'],
'/securityInfo/**':     ['ROLE_ADMIN'],
'/registationCode/**':     ['ROLE_ADMIN'],

2)     Run your app (note this is the first time running your app)

It’s time to create another role, and add a few users, using the Security UI. We will use the admin account we bootstrapped to create the other users and roles. If you want your users to stick around in the database you should open dataSource.groovy and set your dev environment to ‘”update”’ and remove the mem: tag.

3)     Click on your User Controller, (all controller code can found within the plugins directory )
4)     Add ROLE_USER give this role to your admin account
5)     Experiment with the UI


Now go build your app!!


PS: Some Useful Customizations

If you don’t want to use the staticRules area or want to override some security you can use the @Secured tag above each method(). See below.

import grails.plugin.springsecurity.annotation.Secured  ///don’t forget to import this

...
      @Secured ('ROLE_ADMIN'//talking about this
      def yourMethod() {
            Your method code  
            }
...

      @Secured ('ROLE_USER')
      def yourOtherMethod() {
         Your method code  
         }
...

Who’s logged in? Paste this into the bottom of views > layouts > main.gsp  (above </body>)
   

   <nobr>
            <div id='loginLinkContainer'>
                  <sec:ifLoggedIn>
                        Logged in as <sec:username /> (<g:link controller='logout'>Logout</g:link>)
                        </sec:ifLoggedIn>
                  <sec:ifNotLoggedIn>
                        <g:link controller='login'>Login</g:link>
                  </sec:ifNotLoggedIn>

                  <sec:ifSwitched>
                        <href='${request.contextPath}/j_spring_security_exit_user'>
                              Resume as <sec:switchedUserOriginalUsername />
                        </a>
                  </sec:ifSwitched>
            </div>
      </nobr>

      </span>



Syntax in views for current user:    <sec:username />

Syntax in controllers for current user is a little more complicated:   
def springSecurityService // first you have to define the service
springSecurityService.getCurrentUser()  // then you can reference it

If you customize your User domain class, you will also want to customize your User create UI form: 
                  Plugins > spring-security-ui > views > user > create.gsp and edit.gsp

The UI also has user registration and forgot password configuration that we did not use. 


This is an example of controller code that limits current user to the index view:

def springSecurityService // you have to put this someplace in your controller once!

def index() {
def user = User.findByUsername(params.id)  //sends only user related address to view
def loggedInUser = springSecurityService.getCurrentUser();
if (user == loggedInUser) {   //user matches loggedInUser
user : user ]
else {
response.sendError(404)
}
}


That's all folks.

 

3 comments:

  1. Error initializing the application: No such property: Role for class: BootStrap
    Message: No such property: Role for class: BootStrap

    ReplyDelete
  2. thank you so much for this it worked for me in my Grails 3.1.10 Application.
    Thanks Alot.

    ReplyDelete
  3. Can you please help me with using spring security core 2.0.0 for grails 2.5.2

    ReplyDelete