How to create grails core acl(2.5.6)

By | June 5th 2019 01:09:04 PM | viewed 575 times
Step-1

setup database

for MySql connection:

set plugins for MySql connection in the location grails-app\conf\BuildConfig.groovy as follows:

 dependencies {
         runtime 'mysql:mysql-connector-java:5.1.29'
    }

delete existing script and add the following code in the location:grails-app\conf\DataSource.groovy as follows:

dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "com.mysql.jdbc.Driver"
    dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
    username = "root"
    password = ""
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
    cache.region.factory_class = 'org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory' // Hibernate 4
    singleSession = true // configure OSIV singleSession mode
    flush.mode = 'manual' // OSIV session flush mode outside of transactional context
}

// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate', ''
            //url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
			url = "jdbc:mysql://localhost/grailstest"
        }
    }
    test {
        dataSource {
            dbCreate = "update"
             url = "jdbc:mysql://localhost/grailstest"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:mysql://localhost/grailstest"
            properties {
               // See http://grails.org/doc/latest/guide/conf.html#dataSource for documentation
               jmxEnabled = true
               initialSize = 5
               maxActive = 50
               minIdle = 5
               maxIdle = 25
               maxWait = 10000
               maxAge = 10 * 60000
               timeBetweenEvictionRunsMillis = 5000
               minEvictableIdleTimeMillis = 60000
               validationQuery = "SELECT 1"
               validationQueryTimeout = 3
               validationInterval = 15000
               testOnBorrow = true
               testWhileIdle = true
               testOnReturn = false
               jdbcInterceptors = "ConnectionState"
               defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
            }
        }
    }
}

for Oracle connection:

add jdbc driver in the location:D:\grailsproject\erp\lib\ojdbc14.jar

delete existing script and add the following code in the location:grails-app\conf\DataSource.groovy as follows:

dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "oracle.jdbc.OracleDriver"
    dialect = org.hibernate.dialect.Oracle10gDialect

    username = "METAL_HCM_FINAL2"
    password = "METAL_HCM_FINAL2"

}

hibernate {
    singleSession = true
    flush.mode = 'manual'
    cache.use_query_cache = false
    cache.use_second_level_cache = true
    jdbc.use_get_generated_keys = true
    cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory'
}

environments {
    development {
        dataSource {
            dbCreate = "update" // one of 'create', 'create-drop', 'update', 'validate'
              url = "jdbc:oracle:thin:@UKMODAK-PC:1521:db11g"
        }
    }
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:oracle:thin:@HOME-74496774C0:1521:ukmodak"
        }
    }
    production {
        dataSource {
            dbCreate = "update"
             url = "jdbc:oracle:thin:@HOME-74496774C0:1521:ukmodak"
            properties {
                jmxEnabled = true
                initialSize = 5
                maxActive = 50
                minIdle = 5
                maxIdle = 25
                maxWait = 10000
                maxAge = 10 * 60000
                timeBetweenEvictionRunsMillis = 5000
                minEvictableIdleTimeMillis = 60000
                validationQuery = "SELECT 1"
                validationQueryTimeout = 3
                validationInterval = 15000
                testOnBorrow = true
                testWhileIdle = true
                testOnReturn = false
                jdbcInterceptors = "ConnectionState"
                defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED
            }
        }
    }
}

add a model in the following location:D:\grailsproject\uktest\grails-app\domain\com\menu\MnMenu.groovy

package com.menu

class MnMenu {
    Long id
    String menuType
    String linkType
    String menuTitle
    Long parentId
    Integer isActive
    Integer sortingOrder
    String urlPath
    String userRole

    static constraints = {
       menuType nullable: false
       linkType nullable: false
       menuTitle nullable: false,unique: true
       parentId nullable: true
       isActive nullable: true
       sortingOrder nullable: true
       urlPath nullable: false
       userRole nullable: true
    }

    static mapping={
        version false
    }
}

run the following command:

D:\grailsproject\uktest > grails run-app

If mn_menu table create in the database then connection is ok.

Step-2

add spring security core plugins in the location:grails-app\conf\BuildConfig.groovy as follows:


   repositories {
	    mavenRepo 'http://repo.spring.io/milestone'
    }
 
  plugins {
        compile ":spring-security-core:2.0.0"
    }
		
or
D:\grailsproject\uktest >grails clean
D:\grailsproject\uktest >grails install-plugin spring-security-core
Step-3

Now create packahe User UserRole Requestmap model with the folloowing command line

D:\grailsproject\uktest >grails s2-quickstart com.auth(package) AuthUser(model) AuthRole(model) Requestmap(model)

then this tree model will create

Step-4

Now run the following command

D:\grailsproject\uktest >grails run-app

then the following tavle will create

Step-5

For advance acl run the following command

D:\grailsproject\uktest >grails create-acl-domain 

This command will create few other domain classes like AclClass, AclEntry, AclObjectIdentity and AclSid. For example, AclClass will be used to set permission for the particular domain class.

Step-6

Go to location:grailstest\target\work\plugins\spring-security-core-2.0.0\grails-app\controllers\grails\plugin\springsecurity and copy login, logout controller and past in the location: controller/com.login and com.logout

change login and logout controller package as you assign

Go to location:grailstest\target\work\plugins\spring-security-core-2.0.0\grails-app\views\login and copy auth.gsp and deney.gsp and past in the location: view/login/

Step-7

open project in intellij ide and setting assensial jdk library(grails lib),sdk(java lib) from project structute and run.

if run and if login page show then is ok

Step-8

open project in intellij ide and create controller, view of auth domain package respectively using intellij

Step-9

open bootstrap.groovy from the location:grailstest\grails-app\conf\BootStrap.groovy and add the following code for create role, user, some common url permission

  
  def init = { servletContext ->

        def currentDate = new Date()
        def roleAdmin = AuthRole.findByAuthority('ROLE_ADMIN') ?: new AuthRole(authority: 'ROLE_ADMIN').save(flush: true)

        def user = AuthUser.findByUsername('admin') ?: new AuthUser(username: 'admin', password: '123456', enabled: true, accountExpired: false, accountLocked: false, passwordExpired: false).save(flush: true)
        if (!user?.authorities?.contains(roleAdmin)) {


            AuthUserAuthRole.create(user, roleAdmin, true)

            // add some initial request map
            for (String url in [
                    '/index', '/home.gsp', '/**/favicon.ico',
                    '/assets/**', '/**/js/**', '/**/css/**', '/**/images/**',
                    '/login', '/login.*', '/login/*',
                    '/logout', '/logout.*', '/logout/*']) {

                new Requestmap(url: url, configAttribute: 'permitAll').save(flush: true)
            }
        }
            new Requestmap(url: '/resources/**', configAttribute: 'permitAll').save(flush:true)
            new Requestmap(url: '/', configAttribute: 'permitAll').save(flush:true)
            new Requestmap(url: '/requestmap', configAttribute: 'ROLE_ADMIN').save(flush:true)
            new Requestmap(url: '/requestmap/*', configAttribute: 'ROLE_ADMIN').save(flush:true)

    }

to import package put cursor on domain and alt+enter, then package will import

again rerun project from intellij ide

then assign role, user and permission will create on the database

after running the project browse this url:http://localhost:8080/grailstest/login/auth, then login form will show

Step-10

setup default page

Go to location:grailstest\grails-app\conf\UrlMapping.groovy and add the following code

static mappings = {
        "/$controller/$action?/$id?(.$format)?"{
            constraints {
                // apply constraints here
            }
        }
        "/"(controller: "login", action: "auth")
        //"/"(view:"/index")
        "500"(view:'/error')
	}
Step-11

setup login redirect page

Go to location:grailstest\grails-app\conf\spring\Resource.groovy and add the following code


import grails.plugin.springsecurity.SpringSecurityUtils
beans = {

    authenticationSuccessHandler(com.auth.MyAuthSuccessHandlerController) {
        def conf = SpringSecurityUtils.securityConfig;
        requestCache = ref('requestCache');
        defaultTargetUrl = conf.successHandler.defaultTargetUrl;
        alwaysUseDefaultTargetUrl = conf.successHandler.alwaysUseDefault;
        targetUrlParameter = conf.successHandler.targetUrlParameter;
        useReferer = conf.successHandler.useReferer;
        redirectStrategy = ref('redirectStrategy');

        adminUrl = "/requestmap/index";
        applicantUrl = "/irAplcIndex/index";
        employeeUrl = "/hrAdmin/index";
    }

}

Now go to location:com.auth.MyAuthSuccessHandlerController and add the following code


package com.auth

import grails.plugin.springsecurity.SpringSecurityUtils
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

class MyAuthSuccessHandlerController extends SavedRequestAwareAuthenticationSuccessHandler {


    private String applicantUrl;
    private String adminUrl;
    private String employeeUrl;


    def index() {

    }

    @Override
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
       
        boolean hasAdmin = SpringSecurityUtils.ifAnyGranted("ROLE_ADMIN");
        boolean hasApplicant = SpringSecurityUtils.ifAllGranted("ROLE_APPLICANT");
        boolean hasEmployee = SpringSecurityUtils.ifAllGranted("ROLE_EMPLOYEE");


        if(hasAdmin){

            return "/requestmap/index";

        }else if(hasApplicant){

            return "/irAplcIndex/index";

        }else if(hasEmployee){

            return "/hrAdmin/index";

        }else{
            return "/irHomeIndex/index";
        }

    }

    public void setApplicantUrl(String applicantUrl){
        this.applicantUrl = applicantUrl;
    }

    public void setAdminUrl(String adminUrl){
        this.adminUrl = adminUrl;
    }

    public void setEmployeeUrl(String employeeUrl){
        this.employeeUrl = employeeUrl;
    }


}

rerun project and see default home page and admin login page

We can also use the following code in the location:config.groovy as follows:


grails.plugin.springsecurity.auth.loginFormUrl ='/webHome/index'
grails.plugin.springsecurity.successHandler.alwaysUseDefault = true
grails.plugin.springsecurity.successHandler.defaultTargetUrl = '/webHome/index'


bONEandALL
Visitor

Total : 18980

Today :9

Today Visit Country :

  • Germany
  • Singapore
  • United States
  • Russia