SlideShare a Scribd company logo
Spring Security
in Grails
Agenda
Introduction
Domain Classes
Request Mapping to Secure URL
Helper Classes
Introduction
It simplifies the integration of spring security into grails.
Default values are in the plugin’s grails-app/conf/DefaultSecurityConfig.groovy.
We add application specific values in grails-app/conf/Config.groovy.
The two configurations will be merged with application values overriding the
default.
To use spring security simply integrate its plugin as:-
1. plugins{
compile ‘:spring-security-core:2.0-RC4’
}
2. grails compile
3. grails s2-quickstart com User Role
It will create two controller Name (LoginController and LogoutController), one
gsp page (auth.gsp) and three domain (User, Role and UserRole).
Spring Security is more aggressively restricted, so you can do some basic
changes.,
It is Logout POST only, to allow GET access
grails.plugin.springsecurity.logout.postOnly=false
There are other more setting that you can change.
Domain Classes
User
Role
UserRole
Group
UserGroup
GroupRole
Requestmap Class
To use standard user lookup you will need minimum an User and a Role
domain.
To manage many to many relationship between User and Role you need
another domain UserRole.
If you want to store URL<->Role mapping then you need Requestmap domain.
If you want to user User/Group lookup then need Group domain.
To manage many to many relationships between User/Group and Group/Role
you need UserGroup and GroupRole respectively.
User Domain
Spring-security uses and authentication object to determine whether the current
user has right to perform the secured action, such as accessing the URL and
manipulating the other domain object, accessing the secured method and so
on.
The object will be created during the login.
By default plugin uses the grails User domain to manage this data. (username,
password, enabled and others.
In addition you should define authorities to retrieve the role of the user.
getAuthorities() is analogous to define static hasMany=[roles:Role]
Role Domain:-
Spring security also requires an Role class to define the authority to the User.
UserRole:-
The mapping relationship between ‘User' and ‘Role' is a many-to-many.
Users have multiple roles, and roles are shared by multiple users.
This approach can be problematic in Grails, because a popular role, for example, ROLE_USER, will
be granted to many users in your application.
GORM uses collections to manage adding and removing related instances and maps many-to-many
relationships bidirectionally.
The recommended approach in the plugin is to map a domain class to the join table that manages the
many-to-many, and using that to grant and revoke roles to users.
User user=new User(name:”Abc”,
email:”abc@nexthoughts.com,password:”123”).save(flush:true)
Role adminRole=new Role(authority:”ROLE_ADMIN”).save(flush:true)
To add role
UserRole.create(user,adminRole)
To remove role
UserRole.remove(user,adminRole)
How to create a user and assign a role to him
RequestMap Configuration to Secure Url
Define Secured Annotations
Simple Map in Config.groovy
RequestMap Instance saved in database
Pessimistic Lockdown
Some pages in any application is public and some pages are accessible to
only authorized person. Pessimistic approach is default and have to
configuration options:-
rejectIfNoRule
fii.rejectPublicInvocations
rejectIfNoRule:- (true):- then any Url that has no request mappings will be
denied to all users.
fii.rejectPublicInvocations:- (true) Un-mapped Url will trigger
IllegalArgumentException and will show error page.
fii.rejectPublicInvocations:- (false):- You will see Sorry you are not authorized
to view page.
If you want the more obvious error page, set fii.rejectPublicInvocations to true
and rejectIfNoRule to false to allow that check to occur.
To reject un-mapped URLs with a 403 error code, use these settings
grails.plugin.springsecurity.rejectIfNoRule = true
grails.plugin.springsecurity.fii.rejectPublicInvocations = false
To reject with the error 500 page,
grails.plugin.springsecurity.rejectIfNoRule = false
grails.plugin.springsecurity.fii.rejectPublicInvocations = true
Defining Secured Annotations
package com.mycompany.myapp
import grails.plugin.springsecurity.annotation.Secured
class SecureAnnotatedController {
@Secured(['ROLE_ADMIN'])
def index() {
render 'you have ROLE_ADMIN'
}
@Secured(['ROLE_ADMIN', 'ROLE_SUPERUSER'])
def adminEither() {
render 'you have ROLE_ADMIN or SUPERUSER'
}
def anybody() {
render 'anyone can see this' // assuming you're not using "strict" mode
}
}
Simple Map in Config.groovy
grails.plugin.springsecurity.securityConfigType = "InterceptUrlMap"
grails.plugin.springsecurity.interceptUrlMap = [
'/': ['permitAll'],
'/index': ['permitAll'],
'/index.gsp': ['permitAll'],
'/assets/**': ['permitAll'],
'/**/js/**': ['permitAll'],
'/**/css/**': ['permitAll'],
'/**/images/**': ['permitAll'],
'/**/favicon.ico': ['permitAll'],
'/login/**': ['permitAll'],
'/logout/**': ['permitAll'],
'/secure/**': ['ROLE_ADMIN'],
'/finance/**': ['ROLE_FINANCE', 'isFullyAuthenticated()'],
]
Helper Classes
Security TagLib
SpringSecurityService
SpringSecurityUtils
Security TagLib
ifLoggedIn
<sec:ifLoggedIn>
Welcome Back!
</sec:ifLoggedIn>
ifNotLoggedIn
<sec:ifNotLoggedIn>
<g:link controller='login' action='auth'>Login</g:link>
</sec:ifNotLoggedIn>
ifAllGranted
ifAnyGranted
ifNotGranted
loggedInUserInfo
<sec:loggedInUserInfo field="username"/>
username
ifSwitched
ifNotSwitched
access
noAccess
link
Spring Security Service
def springSecurityService
getCurrentUser()
loadCurrentUser()
isLoggedIn()
getAuthentication()
getPrincipal()
encodePassword()
updateRole()
deleteRole()

More Related Content

Similar to Spring security

cloud foundry plugin doc for grails app
cloud foundry plugin doc for grails appcloud foundry plugin doc for grails app
cloud foundry plugin doc for grails appKanaka Durga
 
Groovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: MinneapolisGroovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: MinneapolisJenn Strater
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJSGregor Woiwode
 
intoduction to Grails Framework
intoduction to Grails Frameworkintoduction to Grails Framework
intoduction to Grails FrameworkHarshdeep Kaur
 
Beginning Native Android Apps
Beginning Native Android AppsBeginning Native Android Apps
Beginning Native Android AppsGil Irizarry
 
Migrating from Grails 2 to Grails 3
Migrating from Grails 2 to Grails 3Migrating from Grails 2 to Grails 3
Migrating from Grails 2 to Grails 3Michael Plöd
 
Fun With Spring Security
Fun With Spring SecurityFun With Spring Security
Fun With Spring SecurityBurt Beckwith
 
Debian graylog logging server.docx
Debian graylog logging server.docxDebian graylog logging server.docx
Debian graylog logging server.docxAhmed Swarup
 
Curso Symfony - Clase 3
Curso Symfony - Clase 3Curso Symfony - Clase 3
Curso Symfony - Clase 3Javier Eguiluz
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIEric Wise
 
Play vs Grails Smackdown - Devoxx France 2013
Play vs Grails Smackdown - Devoxx France 2013Play vs Grails Smackdown - Devoxx France 2013
Play vs Grails Smackdown - Devoxx France 2013Matt Raible
 
Config/BuildConfig
Config/BuildConfigConfig/BuildConfig
Config/BuildConfigVijay Shukla
 
JavaScript Patterns and Principles
JavaScript Patterns and PrinciplesJavaScript Patterns and Principles
JavaScript Patterns and PrinciplesAaronius
 
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...D
 

Similar to Spring security (20)

clodfoundrydoc.pdf
clodfoundrydoc.pdfclodfoundrydoc.pdf
clodfoundrydoc.pdf
 
cloud foundry plugin doc for grails app
cloud foundry plugin doc for grails appcloud foundry plugin doc for grails app
cloud foundry plugin doc for grails app
 
Grails Advanced
Grails Advanced Grails Advanced
Grails Advanced
 
Groovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: MinneapolisGroovy Grails Gr8Ladies Women Techmakers: Minneapolis
Groovy Grails Gr8Ladies Women Techmakers: Minneapolis
 
Introduction To Grails
Introduction To GrailsIntroduction To Grails
Introduction To Grails
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJS
 
intoduction to Grails Framework
intoduction to Grails Frameworkintoduction to Grails Framework
intoduction to Grails Framework
 
Grails basics
Grails basics Grails basics
Grails basics
 
Beginning Native Android Apps
Beginning Native Android AppsBeginning Native Android Apps
Beginning Native Android Apps
 
Migrating from Grails 2 to Grails 3
Migrating from Grails 2 to Grails 3Migrating from Grails 2 to Grails 3
Migrating from Grails 2 to Grails 3
 
Fun With Spring Security
Fun With Spring SecurityFun With Spring Security
Fun With Spring Security
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
Debian graylog logging server.docx
Debian graylog logging server.docxDebian graylog logging server.docx
Debian graylog logging server.docx
 
Curso Symfony - Clase 3
Curso Symfony - Clase 3Curso Symfony - Clase 3
Curso Symfony - Clase 3
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
 
Play vs Grails Smackdown - Devoxx France 2013
Play vs Grails Smackdown - Devoxx France 2013Play vs Grails Smackdown - Devoxx France 2013
Play vs Grails Smackdown - Devoxx France 2013
 
Config/BuildConfig
Config/BuildConfigConfig/BuildConfig
Config/BuildConfig
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
JavaScript Patterns and Principles
JavaScript Patterns and PrinciplesJavaScript Patterns and Principles
JavaScript Patterns and Principles
 
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
 

More from Vijay Shukla (19)

Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4
 
Preview of Groovy 3
Preview of Groovy 3Preview of Groovy 3
Preview of Groovy 3
 
Jython
JythonJython
Jython
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
 
Groovy
GroovyGroovy
Groovy
 
Grails services
Grails servicesGrails services
Grails services
 
Grails plugin
Grails pluginGrails plugin
Grails plugin
 
Grails domain
Grails domainGrails domain
Grails domain
 
Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
 
Grails
GrailsGrails
Grails
 
Gorm
GormGorm
Gorm
 
Controller
ControllerController
Controller
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
Command object
Command objectCommand object
Command object
 
Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
 
Vertx
VertxVertx
Vertx
 
Custom plugin
Custom pluginCustom plugin
Custom plugin
 
REST
RESTREST
REST
 
GORM
GORMGORM
GORM
 

Recently uploaded

De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEJelle | Nordend
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...rajkumar669520
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfOrtus Solutions, Corp
 
Benefits of Employee Monitoring Software
Benefits of  Employee Monitoring SoftwareBenefits of  Employee Monitoring Software
Benefits of Employee Monitoring SoftwareMera Monitor
 
How To Build a Successful SaaS Design.pdf
How To Build a Successful SaaS Design.pdfHow To Build a Successful SaaS Design.pdf
How To Build a Successful SaaS Design.pdfayushiqss
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfMeon Technology
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Gáspár Nagy
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with StrimziStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzisteffenkarlsson2
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfVictor Lopez
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAlluxio, Inc.
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisNeo4j
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
 
INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignNeo4j
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdfkalichargn70th171
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessWSO2
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?XfilesPro
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesNeo4j
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
 

Recently uploaded (20)

De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Benefits of Employee Monitoring Software
Benefits of  Employee Monitoring SoftwareBenefits of  Employee Monitoring Software
Benefits of Employee Monitoring Software
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
How To Build a Successful SaaS Design.pdf
How To Build a Successful SaaS Design.pdfHow To Build a Successful SaaS Design.pdf
How To Build a Successful SaaS Design.pdf
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with StrimziStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by Design
 
10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf10 Essential Software Testing Tools You Need to Know About.pdf
10 Essential Software Testing Tools You Need to Know About.pdf
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 

Spring security

  • 3. Introduction It simplifies the integration of spring security into grails. Default values are in the plugin’s grails-app/conf/DefaultSecurityConfig.groovy. We add application specific values in grails-app/conf/Config.groovy. The two configurations will be merged with application values overriding the default. To use spring security simply integrate its plugin as:- 1. plugins{ compile ‘:spring-security-core:2.0-RC4’ }
  • 4. 2. grails compile 3. grails s2-quickstart com User Role It will create two controller Name (LoginController and LogoutController), one gsp page (auth.gsp) and three domain (User, Role and UserRole). Spring Security is more aggressively restricted, so you can do some basic changes., It is Logout POST only, to allow GET access grails.plugin.springsecurity.logout.postOnly=false There are other more setting that you can change.
  • 6. To use standard user lookup you will need minimum an User and a Role domain. To manage many to many relationship between User and Role you need another domain UserRole. If you want to store URL<->Role mapping then you need Requestmap domain. If you want to user User/Group lookup then need Group domain. To manage many to many relationships between User/Group and Group/Role you need UserGroup and GroupRole respectively.
  • 7. User Domain Spring-security uses and authentication object to determine whether the current user has right to perform the secured action, such as accessing the URL and manipulating the other domain object, accessing the secured method and so on. The object will be created during the login. By default plugin uses the grails User domain to manage this data. (username, password, enabled and others. In addition you should define authorities to retrieve the role of the user. getAuthorities() is analogous to define static hasMany=[roles:Role]
  • 8. Role Domain:- Spring security also requires an Role class to define the authority to the User. UserRole:- The mapping relationship between ‘User' and ‘Role' is a many-to-many. Users have multiple roles, and roles are shared by multiple users. This approach can be problematic in Grails, because a popular role, for example, ROLE_USER, will be granted to many users in your application. GORM uses collections to manage adding and removing related instances and maps many-to-many relationships bidirectionally. The recommended approach in the plugin is to map a domain class to the join table that manages the many-to-many, and using that to grant and revoke roles to users.
  • 9. User user=new User(name:”Abc”, email:”abc@nexthoughts.com,password:”123”).save(flush:true) Role adminRole=new Role(authority:”ROLE_ADMIN”).save(flush:true) To add role UserRole.create(user,adminRole) To remove role UserRole.remove(user,adminRole) How to create a user and assign a role to him
  • 10. RequestMap Configuration to Secure Url Define Secured Annotations Simple Map in Config.groovy RequestMap Instance saved in database Pessimistic Lockdown Some pages in any application is public and some pages are accessible to only authorized person. Pessimistic approach is default and have to configuration options:- rejectIfNoRule fii.rejectPublicInvocations
  • 11. rejectIfNoRule:- (true):- then any Url that has no request mappings will be denied to all users. fii.rejectPublicInvocations:- (true) Un-mapped Url will trigger IllegalArgumentException and will show error page. fii.rejectPublicInvocations:- (false):- You will see Sorry you are not authorized to view page. If you want the more obvious error page, set fii.rejectPublicInvocations to true and rejectIfNoRule to false to allow that check to occur.
  • 12. To reject un-mapped URLs with a 403 error code, use these settings grails.plugin.springsecurity.rejectIfNoRule = true grails.plugin.springsecurity.fii.rejectPublicInvocations = false To reject with the error 500 page, grails.plugin.springsecurity.rejectIfNoRule = false grails.plugin.springsecurity.fii.rejectPublicInvocations = true
  • 13. Defining Secured Annotations package com.mycompany.myapp import grails.plugin.springsecurity.annotation.Secured class SecureAnnotatedController { @Secured(['ROLE_ADMIN']) def index() { render 'you have ROLE_ADMIN' } @Secured(['ROLE_ADMIN', 'ROLE_SUPERUSER']) def adminEither() { render 'you have ROLE_ADMIN or SUPERUSER' } def anybody() { render 'anyone can see this' // assuming you're not using "strict" mode } }
  • 14. Simple Map in Config.groovy grails.plugin.springsecurity.securityConfigType = "InterceptUrlMap" grails.plugin.springsecurity.interceptUrlMap = [ '/': ['permitAll'], '/index': ['permitAll'], '/index.gsp': ['permitAll'], '/assets/**': ['permitAll'], '/**/js/**': ['permitAll'], '/**/css/**': ['permitAll'], '/**/images/**': ['permitAll'], '/**/favicon.ico': ['permitAll'], '/login/**': ['permitAll'], '/logout/**': ['permitAll'], '/secure/**': ['ROLE_ADMIN'], '/finance/**': ['ROLE_FINANCE', 'isFullyAuthenticated()'], ]
  • 16. Security TagLib ifLoggedIn <sec:ifLoggedIn> Welcome Back! </sec:ifLoggedIn> ifNotLoggedIn <sec:ifNotLoggedIn> <g:link controller='login' action='auth'>Login</g:link> </sec:ifNotLoggedIn> ifAllGranted ifAnyGranted ifNotGranted
  • 18. Spring Security Service def springSecurityService getCurrentUser() loadCurrentUser() isLoggedIn() getAuthentication() getPrincipal() encodePassword() updateRole() deleteRole()