Grails Spring Security Core Plugin uses

Source: Internet
Author: User
Tags assert manual flush join grails

Spring Security Core Plugin is a powerful access control plug-in for spring, Secure your applications using the powerful Spring security library quickly and easily

Official plugin Address: Http://www.grails.org/plugin/spring-security-core

Official User's Manual: http://grails-plugins.github.com/grails-spring-security-core/docs/manual/

Insert Spring Security Core Plugin in your grails project.

Grails Install-plugin Spring-security-core
If you use IntelliJ idea, you can simply insert the plugin, as shown below




The plug-in is automatically inserted and the plug-in is inserted to start the configuration using the Spring security core plugin.


Detailed use as follows, original address: http://grails-plugins.github.com/grails-spring-security-core/docs/manual/guide/23%20Tutorials.html #23.1%20using%20controller%20annotations%20to%20secure%20urls

Tutorials 23.1 Using Controller Annotations to Secure URLs 1. Create your Grails application.

$ grails Create-app Bookstore
$ CD Bookstore
2. Install the plugin.
$ grails Install-plugin Spring-security-core
3. Create the User and Role domain classes.
$ grails s2-quickstart Com.testapp User Role

You can choose your names for your domain classes and package; These is just examples.

Depending on your database, some domain class names might is valid, especially those relating to security. Before you create names like "User" or "Group", make sure they is not reserved keywords in your database.

The script creates this User class:

Package Com.testapp

Package test

Class User {

Transient Springsecurityservice

String Username String Password Boolean enabled Boolean accountexpired boolean accountlocked boolean passwordexpired

static constraints = {username blank:false, unique:true password Blank:false}

static mapping = {password column: ' Password '}

Set<role> getauthorities () {Userrole.findallbyuser (this). Collect {It.role} as Set}

Def BeforeInsert () {Encodepassword ()}

Def beforeUpdate () {if (IsDirty (' password ')) {Encodepassword ()}}

protected void Encodepassword () {password = Springsecurityservice.encodepassword (password)}}

Earlier versions of the plugin didn ' t include password encryption logic in the domain class, but it makes the code a lot C Leaner.

And this Role class:

Package Com.testapp

Class Role {

String Authority

Static mapping = {Cache true}

static constraints = {authority blank:false, unique:true}}

and a domain class that maps the Many-to-many join class, Userrole:

Package Com.testapp

Import Org.apache.commons.lang.builder.HashCodeBuilder

Class Userrole implements Serializable {

User User Role role

Boolean equals (Other) {if (!) ( Other instanceof Userrole) {return false}

Other.user?. id = = user?. ID && other.role?. id = = role?. ID}

int Hashcode () {def builder = new Hashcodebuilder () if (user) Builder.append (user.id) if (role) Builder.append (role.id) b Uilder.tohashcode ()}

Static userrole get (long userId, long Roleid) {find ' from userrole where User.id=:userid and Role.id=:roleid ', [userid:u Serid, Roleid:roleid]}

Static userrole Create (user user, Role role, Boolean flush = False) {New Userrole (User:user, Role:role). Save (Flush:flu SH, Insert:true)}

Static Boolean remove (user user, Role role, Boolean flush = False) {Userrole instance = userrole.findbyuserandrole (user, role) if (!instance) {return false}

Instance.delete (Flush:flush) True}

static void RemoveAll (user user) {executeupdate ' DELETE from userrole WHERE user=:user ', [User:user]}

Static mapping = {ID composite: [' role ', ' user '] version false}}

It also creates some UI controllers and Gsps:grails-app/controllers/logincontroller.groovy grails-app/controllers/ Logoutcontroller.groovy GRAILS-APP/VIEWS/AUTH.GSP GRAILS-APP/VIEWS/DENIED.GSP

The script has edited Grails-app/conf/config.groovy and added, the configuration for your domain classes. Make sure, the changes is correct.

These generated files is not part of the Plugin-these is your application files. They is examples to get the started, so you can edit them as. They contain the minimum needed for the plugin.

The plugin have no support for CRUD actions and GSPs for your domain classes; The Spring-security-ui plugin would supply a UI for those. So for now you'll create roles and users in Grails-app/conf/bootstrap.groovy. (see step 7.)

4. Create A controller that is restricted by role.

$ grails Create-controller com.testapp.Secure

This command creates Grails-app/controllers/com/testapp/securecontroller.groovy. Add some output so can verify this things is working:

Package Com.testapp

Class Securecontroller {Def index = {render ' Secure access Only '}}

5. Start the server.

$ grails Run-app

6. Before you secure the page, navigate to Http://localhost:8080/bookstore/secure to verify so can see the page Without being logged in.

7. Shut down the app (using ctrl-c) and edit Grails-app/conf/bootstrap.groovy to add the security objects so you NE Ed.

Import com.testapp.Role
import com.testapp.User
import Com.testapp.UserRole

Class BootStrap {

def init = {ServletContext

def adminrole = new Role (authority: ' Role_admin '). Save (flush:true) def userrole = new Role (authority: ' Role_user '). Save (f Lush:true)

def testUser = new User (username: ' Me ', enabled:true, Password: ' Password ') testuser.save (flush:true)

Userrole.create TestUser, Adminrole, True

Assert user.count () = = 1 Assert role.count () = = 2 Assert userrole.count () = = 1}}

Some things to note on the preceding BootStrap.groovy:The example does not use a traditional GORM many-to-many mapping for the user<->role relationship; Instead you is mapping the join table with the Userrole class. This performance optimization helps significantly when many users has one or more common roles. We explicitly flushed the creates because BootStrap does not run in a transaction or Opensessioninview.

8. Edit Grails-app/controllers/securecontroller.groovy to import the annotation class and apply the annotation to res trict access.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.