grails spring security login is not working - grails

I am using grails 2.1.0. I have installed spring-security-core plugin.
When I create user it is creating it. But when I try to login then it shows:
"Sorry, we were not able to find a user with that username and password."
And there is also another fact that is when I use the same password for different user it does not save password with similar encoded value like for user 1 I have used password 123 which is saved in database like this
d535ce213a0e8e4f9e724af47c46eea409ef401c03617b749da618a82890d743
and for user 2 I also used password 123 and this time it is saved like this
0849ea79a2c1bca057ded06c3053fb5bc5d7ba52b50982e73e44894d4f3e0aa6
I don't understand. Can anyone please help me on this ?
my config.groovy >>>
// locations to search for config files that get merged into the main config;
// config files can be ConfigSlurper scripts, Java properties files, or classes
// in the classpath in ConfigSlurper format
// grails.config.locations = [ "classpath:${appName}-config.properties",
// "classpath:${appName}-config.groovy",
// "file:${userHome}/.grails/${appName}-config.properties",
// "file:${userHome}/.grails/${appName}-config.groovy"]
// if (System.properties["${appName}.config.location"]) {
// grails.config.locations << "file:" + System.properties["${appName}.config.location"]
// }
grails.project.groupId = appName // change this to alter the default package name and Maven publishing destination
grails.mime.file.extensions = true // enables the parsing of file extensions from URLs into the request format
grails.mime.use.accept.header = false
grails.mime.types = [
all: '*/*',
atom: 'application/atom+xml',
css: 'text/css',
csv: 'text/csv',
form: 'application/x-www-form-urlencoded',
html: ['text/html','application/xhtml+xml'],
js: 'text/javascript',
json: ['application/json', 'text/json'],
multipartForm: 'multipart/form-data',
rss: 'application/rss+xml',
text: 'text/plain',
xml: ['text/xml', 'application/xml']
]
// URL Mapping Cache Max Size, defaults to 5000
//grails.urlmapping.cache.maxsize = 1000
// What URL patterns should be processed by the resources plugin
grails.resources.adhoc.patterns = ['/images/*', '/css/*', '/js/*', '/plugins/*']
// The default codec used to encode data with ${}
grails.views.default.codec = "none" // none, html, base64
grails.views.gsp.encoding = "UTF-8"
grails.converters.encoding = "UTF-8"
// enable Sitemesh preprocessing of GSP pages
grails.views.gsp.sitemesh.preprocess = true
// scaffolding templates configuration
grails.scaffolding.templates.domainSuffix = 'Instance'
// Set to false to use the new Grails 1.2 JSONBuilder in the render method
grails.json.legacy.builder = false
// enabled native2ascii conversion of i18n properties files
grails.enable.native2ascii = true
// packages to include in Spring bean scanning
grails.spring.bean.packages = []
// whether to disable processing of multi part requests
grails.web.disable.multipart=false
// request parameters to mask when logging exceptions
grails.exceptionresolver.params.exclude = ['password']
// configure auto-caching of queries by default (if false you can cache individual queries with 'cache: true')
grails.hibernate.cache.queries = false
environments {
development {
grails.logging.jul.usebridge = true
}
production {
grails.logging.jul.usebridge = false
// TODO: grails.serverURL = "http://www.changeme.com"
}
}
// log4j configuration
log4j = {
// Example of changing the log pattern for the default console appender:
//
//appenders {
// console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n')
//}
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages', // GSP
'org.codehaus.groovy.grails.web.sitemesh', // layouts
'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
'org.codehaus.groovy.grails.web.mapping', // URL mapping
'org.codehaus.groovy.grails.commons', // core / classloading
'org.codehaus.groovy.grails.plugins', // plugins
'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
'org.springframework',
'org.hibernate',
'net.sf.ehcache.hibernate'
}
// Added by the Spring Security Core plugin:
grails.plugins.springsecurity.userLookup.userDomainClassName = 'common.auth.User'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'common.auth.UserAuthority'
grails.plugins.springsecurity.authority.className = 'common.auth.Authority'
my login controller >>>
import grails.converters.JSON
import javax.servlet.http.HttpServletResponse
import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
import org.springframework.security.authentication.AccountExpiredException
import org.springframework.security.authentication.CredentialsExpiredException
import org.springframework.security.authentication.DisabledException
import org.springframework.security.authentication.LockedException
import org.springframework.security.core.context.SecurityContextHolder as SCH
import org.springframework.security.web.WebAttributes
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
class LoginController {
/**
* Dependency injection for the authenticationTrustResolver.
*/
def authenticationTrustResolver
/**
* Dependency injection for the springSecurityService.
*/
def springSecurityService
/**
* Default action; redirects to 'defaultTargetUrl' if logged in, /login/auth otherwise.
*/
def index = {
if (springSecurityService.isLoggedIn()) {
redirect uri: SpringSecurityUtils.securityConfig.successHandler.defaultTargetUrl
} else {
redirect action: 'auth', params: params
}
}
/**
* Show the login page.
*/
def auth = {
def config = SpringSecurityUtils.securityConfig
if (springSecurityService.isLoggedIn()) {
redirect uri: config.successHandler.defaultTargetUrl
return
}
String view = 'auth'
String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
render view: view, model: [postUrl: postUrl,
rememberMeParameter: config.rememberMe.parameter]
}
/**
* The redirect action for Ajax requests.
*/
def authAjax = {
response.setHeader 'Location', SpringSecurityUtils.securityConfig.auth.ajaxLoginFormUrl
response.sendError HttpServletResponse.SC_UNAUTHORIZED
}
/**
* Show denied page.
*/
def denied = {
if (springSecurityService.isLoggedIn() &&
authenticationTrustResolver.isRememberMe(SCH.context?.authentication)) {
// have cookie but the page is guarded with IS_AUTHENTICATED_FULLY
redirect action: 'full', params: params
}
}
/**
* Login page for users with a remember-me cookie but accessing a IS_AUTHENTICATED_FULLY page.
*/
def full = {
def config = SpringSecurityUtils.securityConfig
render view: 'auth', params: params,
model: [hasCookie: authenticationTrustResolver.isRememberMe(SCH.context?.authentication),
postUrl: "${request.contextPath}${config.apf.filterProcessesUrl}"]
}
/**
* Callback after a failed login. Redirects to the auth page with a warning message.
*/
def authfail = {
def username = session[UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY]
String msg = ''
def exception = session[WebAttributes.AUTHENTICATION_EXCEPTION]
if (exception) {
if (exception instanceof AccountExpiredException) {
msg = g.message(code: "springSecurity.errors.login.expired")
} else if (exception instanceof CredentialsExpiredException) {
msg = g.message(code: "springSecurity.errors.login.passwordExpired")
} else if (exception instanceof DisabledException) {
msg = g.message(code: "springSecurity.errors.login.disabled")
} else if (exception instanceof LockedException) {
msg = g.message(code: "springSecurity.errors.login.locked")
} else {
msg = g.message(code: "springSecurity.errors.login.fail")
}
}
if (springSecurityService.isAjax(request)) {
render([error: msg] as JSON)
} else {
flash.message = msg
redirect action: 'auth', params: params
}
}
/**
* The Ajax success redirect url.
*/
def ajaxSuccess = {
render([success: true, username: springSecurityService.authentication.name] as JSON)
}
/**
* The Ajax denied redirect url.
*/
def ajaxDenied = {
render([error: 'access denied'] as JSON)
}
}
my authority.groovy >>>
package common.auth
class Authority {
String authority
static mapping = {
cache true
}
static constraints = {
authority blank: false, unique: true
}
}
my user domain.groovy where my user will be saved >>>
package common.auth
class User {
transient springSecurityService
String realname
String username
String password
String designation
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
static constraints = {
username blank: false, unique: true
password blank: false
}
static mapping = {
password column: '`password`'
}
Set<Authority> getAuthorities() {
UserAuthority.findAllByUser(this).collect { it.authority } as Set
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
}
my userauthority.groovy >>>
package common.auth
import org.apache.commons.lang.builder.HashCodeBuilder
class UserAuthority implements Serializable {
User user
Authority authority
boolean equals(other) {
if (!(other instanceof UserAuthority)) {
return false
}
other.user?.id == user?.id &&
other.authority?.id == authority?.id
}
int hashCode() {
def builder = new HashCodeBuilder()
if (user) builder.append(user.id)
if (authority) builder.append(authority.id)
builder.toHashCode()
}
static UserAuthority get(long userId, long authorityId) {
find 'from UserAuthority where user.id=:userId and authority.id=:authorityId',
[userId: userId, authorityId: authorityId]
}
static UserAuthority create(User user, Authority authority, boolean flush = false) {
new UserAuthority(user: user, authority: authority).save(flush: flush, insert: true)
}
static boolean remove(User user, Authority authority, boolean flush = false) {
UserAuthority instance = UserAuthority.findByUserAndAuthority(user, authority)
if (!instance) {
return false
}
instance.delete(flush: flush)
true
}
static void removeAll(User user) {
executeUpdate 'DELETE FROM UserAuthority WHERE user=:user', [user: user]
}
static void removeAll(Authority authority) {
executeUpdate 'DELETE FROM UserAuthority WHERE authority=:authority', [authority: authority]
}
static mapping = {
id composite: ['authority', 'user']
version false
}
}
And my createUser action to create user in AdministratorActionController >>>
package administrator
import common.auth.User
class AdmistratorActionController {
def springSecurityService
def index() {
redirect(controller: 'admistratorAction', action: 'createUser')
}
def createUser = {
User user = new User(params)
def password = user.password
def salt = user.username //depends on what you're using as a salt
user.password = springSecurityService.encodePassword(password, salt)
user.save()
flash.message = "User Create Successfully !!!"
}
}

I think you are encoding your password twice, you already have encode() on beforeInsert in the domain, I think you need not to encode it again.

Spring Security use hash of user password + a salt. Salt is used to defeat pre-computed rainbow table attacks that could otherwise be used to greatly improve the efficiency of cracking the hashed password database. See http://en.wikipedia.org/wiki/Salt_(cryptography)
For example, if we're using username as a hash, real value in database will be:
md5(user.password + '|' + user.username)
So for two different userw with same password:
user: username: 'user1', password: 123
user: username: 'user2', password: 123
you'll get two different values in database:
md5('user1|123') == 975204d0650cc642730866d56f66b6fb
md5('user2|123') == aa12022115555842a7f80564940ae49d
So, if hacker have access to you database he cannot guess the password.
Spring Security uses same hashing function and salt for saving and loading user. And if it unable to find user it probably means that you've used different salt for initial save and for later load from the database. Make sure that you have same salt source, and it's not changing (like id field, that have null value when you just creating a new user)

Related

Spring UI RegisterController - No such property

I am using grails 2.3.4 with ":spring-security-ui:1.0-RC1" and ':spring-security-core:2.0-RC2' plugin. I have configured both plugins in the Config.groovy like that:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.SaaSTemplate.auth.Person'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.SaaSTemplate.auth.PersonRole'
grails.plugin.springsecurity.authority.className = 'com.SaaSTemplate.auth.Role'
//**********************************
// Spring Security UI Settings
//**********************************
//password validation of RegisterController.groovy
grails.plugin.springsecurity.ui.password.validationRegex='^.*(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!##$%^&]).*$' //example: 1Test#!!
grails.plugin.springsecurity.ui.password.minLength=8
grails.plugin.springsecurity.ui.password.maxLength=64
My RegisterController.groovy looks like that:
#Secured(['permitAll'])
class RegisterController extends grails.plugin.springsecurity.ui.RegisterController {
// override default value from base class
static defaultAction = 'index'
// override default value from base class
static allowedMethods = [register: 'POST']
def mailService
def messageSource
def saltSource
def index() {
def copy = [:] + (flash.chainedParams ?: [:])
copy.remove 'controller'
copy.remove 'action'
[command: new RegisterCommand(copy)] // here is where I get the exception!!!!
}
def register(RegisterCommand command) {
if (command.hasErrors()) {
render view: 'index', model: [command: command]
return
}
String salt = saltSource instanceof NullSaltSource ? null : command.username
def user = lookupUserClass().newInstance(email: command.email, username: command.username,
accountLocked: true, enabled: true)
RegistrationCode registrationCode = springSecurityUiService.register(user, command.password, salt)
if (registrationCode == null || registrationCode.hasErrors()) {
// null means problem creating the user
flash.error = message(code: 'spring.security.ui.register.miscError')
flash.chainedParams = params
redirect action: 'index'
return
}
String url = generateLink('verifyRegistration', [t: registrationCode.token])
def conf = SpringSecurityUtils.securityConfig
def body = conf.ui.register.emailBody
if (body.contains('$')) {
body = evaluate(body, [user: user, url: url])
}
mailService.sendMail {
to command.email
from conf.ui.register.emailFrom
subject conf.ui.register.emailSubject
html body.toString()
}
render view: 'index', model: [emailSent: true]
}
def verifyRegistration() {
def conf = SpringSecurityUtils.securityConfig
String defaultTargetUrl = conf.successHandler.defaultTargetUrl
String token = params.t
def registrationCode = token ? RegistrationCode.findByToken(token) : null
if (!registrationCode) {
flash.error = message(code: 'spring.security.ui.register.badCode')
redirect uri: defaultTargetUrl
return
}
def user
// TODO to ui service
RegistrationCode.withTransaction { status ->
String usernameFieldName = SpringSecurityUtils.securityConfig.userLookup.usernamePropertyName
user = lookupUserClass().findWhere((usernameFieldName): registrationCode.username)
if (!user) {
return
}
user.accountLocked = false
user.save(flush:true)
def UserRole = lookupUserRoleClass()
def Role = lookupRoleClass()
for (roleName in conf.ui.register.defaultRoleNames) {
UserRole.create user, Role.findByAuthority(roleName)
}
registrationCode.delete()
}
if (!user) {
flash.error = message(code: 'spring.security.ui.register.badCode')
redirect uri: defaultTargetUrl
return
}
springSecurityService.reauthenticate user.username
flash.message = message(code: 'spring.security.ui.register.complete')
redirect uri: conf.ui.register.postRegisterUrl ?: defaultTargetUrl
}
def forgotPassword() {
if (!request.post) {
// show the form
return
}
String username = params.username
if (!username) {
flash.error = message(code: 'spring.security.ui.forgotPassword.username.missing')
redirect action: 'forgotPassword'
return
}
String usernameFieldName = SpringSecurityUtils.securityConfig.userLookup.usernamePropertyName
def user = lookupUserClass().findWhere((usernameFieldName): username)
if (!user) {
flash.error = message(code: 'spring.security.ui.forgotPassword.user.notFound')
redirect action: 'forgotPassword'
return
}
def registrationCode = new RegistrationCode(username: user."$usernameFieldName")
registrationCode.save(flush: true)
String url = generateLink('resetPassword', [t: registrationCode.token])
def conf = SpringSecurityUtils.securityConfig
def body = conf.ui.forgotPassword.emailBody
if (body.contains('$')) {
body = evaluate(body, [user: user, url: url])
}
mailService.sendMail {
to user.email
from conf.ui.forgotPassword.emailFrom
subject conf.ui.forgotPassword.emailSubject
html body.toString()
}
[emailSent: true]
}
def resetPassword(ResetPasswordCommand command) {
String token = params.t
def registrationCode = token ? RegistrationCode.findByToken(token) : null
if (!registrationCode) {
flash.error = message(code: 'spring.security.ui.resetPassword.badCode')
redirect uri: SpringSecurityUtils.securityConfig.successHandler.defaultTargetUrl
return
}
if (!request.post) {
return [token: token, command: new ResetPasswordCommand()]
}
command.username = registrationCode.username
command.validate()
if (command.hasErrors()) {
return [token: token, command: command]
}
String salt = saltSource instanceof NullSaltSource ? null : registrationCode.username
RegistrationCode.withTransaction { status ->
String usernameFieldName = SpringSecurityUtils.securityConfig.userLookup.usernamePropertyName
def user = lookupUserClass().findWhere((usernameFieldName): registrationCode.username)
user.password = springSecurityUiService.encodePassword(command.password, salt)
user.save()
registrationCode.delete()
}
springSecurityService.reauthenticate registrationCode.username
flash.message = message(code: 'spring.security.ui.resetPassword.success')
def conf = SpringSecurityUtils.securityConfig
String postResetUrl = conf.ui.register.postResetUrl ?: conf.successHandler.defaultTargetUrl
redirect uri: postResetUrl
}
protected String generateLink(String action, linkParams) {
createLink(base: "$request.scheme://$request.serverName:$request.serverPort$request.contextPath",
controller: 'register', action: action,
params: linkParams)
}
protected String evaluate(s, binding) {
new SimpleTemplateEngine().createTemplate(s).make(binding)
}
// static final passwordValidator = { String password, command ->
// if (command.username && command.username.equals(password)) {
// return 'command.password.error.username'
// }
//
// if (!checkPasswordMinLength(password, command) ||
// !checkPasswordMaxLength(password, command) ||
// !checkPasswordRegex(password, command)) {
// return 'command.password.error.strength'
// }
// }
static boolean checkPasswordMinLength(String password, command) {
def conf = SpringSecurityUtils.securityConfig
int minLength = conf.ui.password.minLength instanceof Number ? conf.ui.password.minLength : 8
password && password.length() >= minLength
}
static boolean checkPasswordMaxLength(String password, command) {
def conf = SpringSecurityUtils.securityConfig
int maxLength = conf.ui.password.maxLength instanceof Number ? conf.ui.password.maxLength : 64
password && password.length() <= maxLength
}
static boolean checkPasswordRegex(String password, command) {
def conf = SpringSecurityUtils.securityConfig
String passValidationRegex = conf.ui.password.validationRegex ?:
'^.*(?=.*\\d)(?=.*[a-zA-Z])(?=.*[!##$%^&]).*$'
password && password.matches(passValidationRegex)
}
// static final password2Validator = { value, command ->
// if (command.password != command.password2) {
// return 'command.password2.error.mismatch'
// }
// }
}
class RegisterCommand {
String username
String email
String password
String password2
def grailsApplication
static constraints = {
username blank: false, validator: { value, command ->
if (value) {
def User = command.grailsApplication.getDomainClass(
SpringSecurityUtils.securityConfig.userLookup.userDomainClassName).clazz
if (User.findByUsername(value)) {
return 'registerCommand.username.unique'
}
}
}
email blank: false, email: true
password blank: false, validator: RegisterController.passwordValidator
password2 validator: RegisterController.password2Validator
}
}
class ResetPasswordCommand {
String username
String password
String password2
static constraints = {
password blank: false, validator: RegisterController.passwordValidator
password2 validator: RegisterController.password2Validator
}
}
As you can see I have just copied the original controller from the source code. Therefore the other classes ResetPasswordCommand and RegisterCommand are also included. However, I still get the exception:
ui.SpringSecurityUiService problem creating Person: com.TestApp.auth.Person : (unsaved)
Die Eigenschaft [firstName] des Typs [class com.TestApp.auth.Person] darf nicht null sein
Die Eigenschaft [lastName] des Typs [class com.TestApp.auth.Person] darf nicht null sein
errors.GrailsExceptionResolver MissingPropertyException occurred when processing request: [GET] /TestApp/register/index
No such property: format for class: TestApp.Register.RegisterCommand. Stacktrace follows:
groovy.lang.MissingPropertyException: No such property: format for class: TestApp.Register.RegisterCommand
at TestApp.Register.RegisterController.index(RegisterController.groovy:26)
at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:200)
at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
at grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter.doFilter(GrailsAnonymousAuthenticationFilter.java:53)
at grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter.doFilter(RequestHolderAuthenticationFilter.java:49)
at grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter.doFilter(MutableLogoutFilter.java:82)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Why do I get this exception? I have included the class RegisterCommand (as also in the original source) in my file?
I really appreciate your input!
UPDATE
I changed my method like that:
def index() {
def copy = [:] + (flash.chainedParams ?: [:])
copy.remove 'controller'
copy.remove 'action'
['controller', 'action', 'format'].each { copy.remove it }
[command: new RegisterCommand(copy)]
}
However, now I still cannot process the registration, I get:
....ui.SpringSecurityUiService problem creating Person: com.TestApp.auth.Person : (unsaved)
The property [firstName] of the type [class com.TestApp.auth.Person] cannot be null
The property [lastName] of the type [class com.TestApp.auth.Person] cannot be null
format is added in the UrlMapping as an optional field.
"/$controller/$action?/$id?(.$format)?"{
constraints {
// apply constraints here
}
}
So you would end up removing that from the map as done for action and controller.
//index action
['controller', 'action', 'format'].each { copy.remove it }
Another option will be to explicitly use bindData to avoid this collision
//index action
RegisterCommand cmd = new RegisterCommand()
bindData copy, cmd

Grails Spring Security authentication from a service

Since i've been using a dedicated service in my Grails app so as to make authentication working with a vaadin UI, i 'm having a problem to validate the login:
1) A new user is created in bootstrap and recorded to db (postgre)
User.withTransaction {
User test = new User(
username: "test",
password: springSecurityService.encodePassword("password"),
enabled: true,
accountExpired: false,
accountLocked: false,
passwordExpired: false
).save()
Role dashManager = new Role(authority: "ROLE_USER").save()
new UserRole(user: test, role: dashManager).save()
2) The vaadin ui calls normally the grails service
boolean login(String username, String password) {
try {
println username + "----" + password
security.signIn(username, password)
return true
} catch (SecurityServiceException e) {
Notification.show("Login/Password incorrect", Notification.TYPE_ERROR_MESSAGE);
return false
}
}
3) My securityService always returns invalid
import grails.transaction.Transactional
import org.springframework.security.core.context.SecurityContextHolder as SCH
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
#Transactional
class SecurityService {
def springSecurityService
def authenticationManager
void signIn(String username, String password) {
try {
def authentication = new UsernamePasswordAuthenticationToken(username, password)
SCH.context.authentication = authenticationManager.authenticate(authentication)
} catch (BadCredentialsException e) {
throw new SecurityException("Invalid username/password")
}
}
void signOut() {
SCH.context.authentication = null
}
boolean isSignedIn() {
return springSecurityService.isLoggedIn()
}
}
You're probably double-encoding the password. Recent versions of the plugin generate a user/person domain class that encodes the password for you, so you don't need to call springSecurityService.encodePassword("password"), and if you do then it's encoded twice. This should work:
User test = new User(
username: "test",
password: "password",
enabled: true
).save()
I omitted setting accountExpired, accountLocked, and passwordExpired to false since those are the default values.
Use the springSecurityService to authenticate
void signIn(String username, String password) {
try {
springSecurityService.reauthenticate(username, password)
} catch (BadCredentialsException e) {
throw new SecurityException("Invalid username/password")
}
}

With specified username getting 'Sorry, we were not able to find a user with that username and password.' message when logging int

I have installed the grails Spring-Security plugin:
plugins {
compile ':spring-security-core:2.0-RC2'
}
Then I used the grails s2-quickstart com.jane Person Role command to create the needed domain classes.
As I have my own User class I refactored the code to use my User class:
package com.jane
class User {
transient springSecurityService
String email
String name
String password
Boolean isAgreeTerms = false
Date agreeTermsDt
Boolean isActive = false
Boolean isBlocked = false
Date dateCreated
Integer createdBy = 0
Date lastUpdated
Integer modifiedBy = 0
static transients = [ 'springSecurityService' ]
static hasMany = [ userProductTier: UserProductTier ]
static mapping = {
id column: "userID"
dateCreated column: 'createdDt'
lastUpdated column: 'modifiedDT'
}
static constraints = {
email blank: false, email: true, unique: true, size: 5..100
name blank: false, size: 3..50
password blank: false
}
void beforeInsert() {
if ( isAgreeTerms ) {
agreeTermsDt = new Date()
}
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
}
I then modified the config.groovy file to:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'com.jane.User'
grails.plugin.springsecurity.userLookup.usernamePropertyName = 'email'
grails.plugin.springsecurity.userLookup.enabledPropertyName = 'isActive'
grails.plugin.springsecurity.userLookup.accountExpiredPropertyName = 'isBlocked'
grails.plugin.springsecurity.userLookup.accountLockedPropertyName = 'isBlocked'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'com.jane.UserRole'
grails.plugin.springsecurity.authority.className = 'com.jane.Role'
I can create users fine, verify they are in the database, have verified that encodePassword is called once. But every time I try to login I get the following error:
Sorry, we were not able to find a user with that username and
password.
And here is the service method to create users:
User createTeamLeader( String name, String email, String password, Boolean isAgreeTerms, Integer productTierId ) {
User user = new User( name: name, email: email, password: password, isAgreeTerms: isAgreeTerms, isActive: true)
UserProductTier userProductTier = new UserProductTier( productTierId: productTierId )
user.addToUserProductTier( userProductTier )
user.save()
UserRole.create( user, Role.findByAuthority('ROLE_USER'), true )
UserRole.create( user, Role.findByAuthority('ROLE_LEAD'), true )
user
}
Often adding debug logging helps, since Spring Security logs a lot at the debug level:
log4j = {
...
debug 'org.springframework.security'
}
In this case it didn't show the problem, so I added an event listener to see if there was information in the failure event:
grails.plugin.springsecurity.useSecurityEventListener = true
grails.plugin.springsecurity.onAbstractAuthenticationFailureEvent = { e, appCtx ->
println "\nERROR auth failed for user $e.authentication.name: $e.exception.message\n"
}
That displayed this:
ERROR auth failed for user ernie#ss.com: No such property: authorities for class: com.jane.User
When you made changes in the class, you removed the getAuthorities method that was in the original version, and is used by the UserDetailsService to determine granted roles during authentication. Adding it back got things working:
Set<Role> getAuthorities() {
UserRole.findAllByUser(this).collect { it.role } as Set
}

Grails : Error initializing spring security on server restart

I have a very strange behaviour on a production server.
When I start for the first time my server, there is no problem, but when I want to stop and restart it, I get the following error :
Configuring Spring Security Core ...
... finished configuring Spring Security Core
2013-10-31 12:03:08,156 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing the application: null
java.lang.NullPointerException
at com.aftmevent.security.UserRole.create(UserRole.groovy:32)
at BootStrap$_closure1.doCall(BootStrap.groovy:16)
at grails.util.Environment.evaluateEnvironmentSpecificBlock(Environment.java:308)
at grails.util.Environment.executeForEnvironment(Environment.java:301)
at grails.util.Environment.executeForCurrentEnvironment(Environment.java:277)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
2013-10-31 12:03:08,156 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing Grails: null
java.lang.NullPointerException
at com.aftmevent.security.UserRole.create(UserRole.groovy:32)
at BootStrap$_closure1.doCall(BootStrap.groovy:16)
at grails.util.Environment.evaluateEnvironmentSpecificBlock(Environment.java:308)
at grails.util.Environment.executeForEnvironment(Environment.java:301)
at grails.util.Environment.executeForCurrentEnvironment(Environment.java:277)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
oct. 31, 2013 12:03:08 PM org.apache.catalina.core.StandardContext startInternal
Here is my BootStrap.groovy :
class BootStrap {
def springSecurityService
def init = { servletContext ->
def existingAdminRole = Role.findByAuthority('ROLE_ADMIN')
def existingUserRole = null
def existingAdminUser = null
if (existingAdminRole) {
existingUserRole = UserRole.findByRole(existingAdminRole)
}
if (existingUserRole) {
existingAdminUser = existingUserRole.user
}
if (!existingAdminUser) {
def adminRole = new Role(authority: 'ROLE_ADMIN')
def adminUser = new User(username: 'admin', password: 'admin', enabled: true)
if (adminRole.validate()) {
adminRole.save(flush: true, failOnError: true)
}
if (adminUser.validate()) {
adminUser.save(flush: true, failOnError: true)
}
UserRole userRole = UserRole.create(adminUser, adminRole, true)
if (userRole.validate()) {
userRole.save(flush: true, failOnError: true)
}
}
}
def destroy = {
}
}
Here is my User.groovy (adding the nullable constraint did not solve the problem) :
User.groovy :
class User {
transient springSecurityService
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
static constraints = {
username nullable: true, blank: false, unique: true
password nullable: true, 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)
}
}
Here are my classe Role.groovy and UserRole.groovy :
Role.groovy :
class Role {
String authority
static mapping = {
cache true
}
static constraints = {
authority nullable: true, blank: false, unique: true
}
}
UserRole.groovy :
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)
builder.toHashCode()
}
static UserRole get(long userId, long roleId) {
find 'from UserRole where user.id=:userId and role.id=:roleId',
[userId: userId, roleId: roleId]
}
static UserRole create(User user, Role role, boolean flush = false) {
new UserRole(user: user, role: role).save(flush: flush, 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 void removeAll(Role role) {
executeUpdate 'DELETE FROM UserRole WHERE role=:role', [role: role]
}
static mapping = {
id composite: ['role', 'user']
version false
}
}
Here is my DataSource.groovy file with the database settings :
environments {
development {
dataSource {
dbCreate = "create-drop" // one of 'create', 'create-drop', 'update', 'validate', ''
driverClassName = 'com.mysql.jdbc.Driver'
username = 'root'
password = 'root'
url = 'jdbc:mysql://localhost:3306/database?autoreconnect=true&useUnicode=true&characterEncoding=utf-8'
}
}
test {
dataSource {
dbCreate = "update"
url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000"
}
}
production {
dataSource {
dbCreate = 'create-drop'
driverClassName = 'com.mysql.jdbc.Driver'
username = 'root'
password = 'root'
url = 'jdbc:mysql://localhost:3306/database?autoreconnect=true&useUnicode=true&characterEncoding=utf-8'
}
}
}
I really don't have any idea about what occured.
I have added the nullable constrainst, trying to put the databe into 'create-drop' / 'update'.
Funny thing : When I drop the databse then create it again, the first server start is good, but crash after a restart.
I try to put println logs into my BootStrap.groovy, I can see them into development environment, but not into production server.
So I'm not sure if my BootStrap is updated creating war.
I create the war using :
grails prod war target/my-new-war-0.0.x.war
Thanks for reading,
Snite
I'm not really sure what's wrong with your code, however your giant block of code was making my head hurt so I had to post this.
Role role = Role.findByAuthority("ROLE_ADMIN") ?: new Role(authority: "ROLE_ADMIN").save(flush: true, failOnError: true)
if (UserRole.countByRole(role) == 0) {
User user = new User(username: 'admin', password: 'admin', enabled: true).save(flush: true, failOnError: true)
UserRole.create(user, role, true)
}
hmmm well its a null point exception:
ERROR context.GrailsContextLoader - Error initializing the application: null
java.lang.NullPointerException
at com.aftmevent.security.UserRole.create(UserRole.groovy:32)
at BootStrap$_closure1.doCall(BootStrap.groovy:16)
Unsure if the pasted content matches up exactly to your own line numbers, something you could try for now is by going around and adding the question mark :
def existingAdminRole = Role.findByAuthority('ROLE_ADMIN')
def existingUserRole = null
def existingAdminUser = null
if (existingAdminRole) {
existingUserRole = UserRole.findByRole(existingAdminRole)
}
if (existingUserRole) {
existingAdminUser = existingUserRole.user
}
change to:
def existingAdminRole = Role?.findByAuthority('ROLE_ADMIN')
def existingUserRole = null
def existingAdminUser = null
if (existingAdminRole) {
existingUserRole = UserRole?.findByRole(existingAdminRole)
}
if (existingUserRole) {
existingAdminUser = existingUserRole?.user
}
Also you could try findorsavewhere rather than an attempt to generate a new record:
https://github.com/vahidhedayati/ajaxdependancyselectexample/blob/master/grails-app/conf/BootStrap.groovy
def n1=MyContinent.findOrSaveWhere(continentName: 'Asia')
def n2=MyContinent.findOrSaveWhere(continentName: 'Europe')
// Create countries and provde continent map value as above defs
def c1 = MyCountry.findOrSaveWhere(mycontinent: n2, countryName:'United Kingdom',ccode:'GB',language:'')
def c2 = MyCountry.findOrSaveWhere(mycontinent: n2, countryName:'France',ccode:'FR',language:'')
def c3 = MyCountry.findOrSaveWhere(mycontinent: n1, countryName:'China',ccode:'CN',language:'')
def c4 = MyCountry.findOrSaveWhere(mycontinent: n1, countryName:'India',ccode:'IN',language:'')
you will need to figure out what is going on in line 32 of UserRole which will be the start of your issue followed by BootStrap on line 16..
Thanks for all of your answer which help me to solve my issue.
It was stupid but in my rundeck script to deploy the war on the production server, it was an out of date version of the war which was used -_-
So doint it manually with the correct war version solve my problem.
Thanks because your advices help me to read adequat documentation on grails's framework and help me thinking looking here.
Cheers,
Snite

Grails 2 can't login with spring security when using multiple databases

On Grails 2.0.3, I installed Spring Security Core and created the User, UserRole and Role objects as per the tutorial: http://blog.springsource.org/2010/08/11/simplified-spring-security-with-grails/
All went fine until I decided to add a second datasource in preparation for accessing objects from a different database. DataSource.groovy looks like this:
test {
dataSource_product {
dbCreate = "update"
url = "jdbc:mysql://localhost/products"
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
username = "blah"
password = "blah"
loggingSql = true
dialect = 'org.hibernate.dialect.MySQL5InnoDBDialect'
}
dataSource {
dbCreate = "update"
url = "jdbc:mysql://localhost/core"
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
username = "blah"
password = "blah"
loggingSql = true
dialect = 'org.hibernate.dialect.MySQL5InnoDBDialect'
}
}
Now I can't log in - even though all I have done is add datasource_product. If I comment this out and recreating the users (in Bootstrap.groovy) then I can log in again. Bootstrap.groovy contains:
def init =
{ servletContext ->
// Add in roles
Role.withTransaction {
def adminRole = Role.findByAuthority ( Role.ROLE_ADMIN ) ?: new Role ( authority: Role.ROLE_ADMIN ).save ( failOnError: true )
def adminUser = User.findByUsername ( 'admin' ) ?: new User (
username: 'blah',
password: 'blah',
enabled: true ).save ( failOnError: true )
if ( !adminUser.authorities.contains ( adminRole ) ) UserRole.create ( adminUser, adminRole )
}
Any ideas?
Gaaaahh. Found this: http://jira.grails.org/browse/GRAILS-8237 - apparently, beforeInsert gets called on each domain for every datasource. This means that, in my User object encodePassword is getting called twice - I'm double-encoding the password:
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password'))
encodePassword()
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
I saw a patch in the JIRA, but until it gets into the release, I created a workaround using an isPasswordEncoded flag to prevent multiple encodes in User:
class User {
boolean isPasswordEncoded = false
....snip....
def beforeInsert() {
if ( !isPasswordEncoded )
{
isPasswordEncoded = true
encodePassword ()
}
}
def beforeUpdate() {
if (isDirty('password')) {
isPasswordEncoded = false
encodePassword()
}
}
....snip....
}
Code solution posted by original answer doesn't work for update. And also doesn't consider multiple updates to same object instance. I use separate flags for insert and update operations, mark them as transient so they're not persisted, and use the afterUpdate() event handler to reset these flags.
static transients = ['beforeInsertRunOnce','beforeUpdateRunOnce']
boolean beforeInsertRunOnce
boolean beforeUpdateRunOnce
def beforeInsert() {
if (! beforeInsertRunOnce) {
beforeInsertRunOnce = true
encodePassword()
}
}
def afterInsert() {
beforeInsertRunOnce = false
}
def beforeUpdate() {
if (isDirty('password') && ! beforeUpdateRunOnce ) {
beforeUpdateRunOnce = true
encodePassword()
}
}
def afterUpdate() {
beforeUpdateRunOnce = false
}
I did have similar issue. Was because I've forgotten to add
grails.plugin.springsecurity.userLookup.userDomainClassName ='yourpackage.User'
grails.plugin.springsecurity.userLookup.authorityJoinClassName =yourpackage.UserRole'
grails.plugin.springsecurity.authority.className ='yourpackage.Role'
After that authentication was working.

Resources