The grails Spring security Core Plugin uses

Source: Internet
Author: User
Tags assert manual flush grails

Spring Security Core Plugin is a powerful privilege 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 Use manual: http://grails-plugins.github.com/grails-spring-security-core/docs/manual/

Insert the spring security Core Plugin in the Grails project.

Grails Install-plugin Spring-security-core
If you use IntelliJ idea, you can easily insert the plugin, as shown in the following figure




The system will automatically insert the plug-in, insert the plug-in can start to configure the use of the spring security core plug-in


Detailed use of the following, the 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

Can choose your names for your domain classes and package; These are just examples.

Depending on your database, some domain class names might not is valid, especially those to security. Before you create names like "User" or "Group", make sure they are 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

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 are correct.

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

The plugin has no support for CRUD actions and GSPs for your domain classes; The Spring-security-ui plugin would supply a UI for those. So, you'll create roles and users in Grails-app/conf/bootstrap.groovy. (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 your can verify that things are working:

Package Com.testapp

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

5. Start the server.

$ grails Run-app

6. Before you are secure the page, navigate to Http://localhost:8080/bookstore/secure to verify so you can 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 which 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 "about the preceding BootStrap.groovy:The example does not use a traditional GORM many-to-many mapping for the user<->role relationship; Instead you are mapping the join table with the Userrole class. This performance optimization helps significantly when many users have one or more common. 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.