Grails Spring Security Core unable to log in - grails

Installed spring-security-core 2.0-RC2 (with grails 2.3.6), ran the quick start but I'm not able to log in. Each time I try, I get the 'Sorry, we were not able to find a user with that username and password.' error.
Done some research and I'm not double encoding the password or nor am I using salt (from what I can tell). I've used earlier versions in other projects, so not sure what's going on. I've also dropped the encodePassword() from the domain class and verified in the DB that it's what I expect it to be
Here's my User domain class:
class User {
transient springSecurityService
String username
String password
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
static transients = ['springSecurityService']
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)
}
}
and my Bootstrap:
def adminRole = new Role(authority: 'ROLE_ADMIN').save(flush: true)
def userRole = new Role(authority: 'ROLE_USER').save(flush: true)
def testUser = new User(username: 'me', password: 'me')
testUser.save(flush: true)
UserRole.create testUser, adminRole, true
UserRole.create testUser, userRole, true
any idea of what I'm doing wrong?
Thanks!

That looks fine, but funny things can be happening under the hood. I wrote up a couple of blog posts to help diagnose issues like this. Check out http://burtbeckwith.com/blog/?p=2003 and http://burtbeckwith.com/blog/?p=2029

Related

customize the person class (replace the username and password attributes)

I'm trying to replace the username with "email" and the password with "motDePasse" but I can't figure out how to do It: I tried to replace every old name by new name in the Person class and I added the following configuration to
my application.groovy :
grails.plugin.springsecurity.userLookup.usernamePropertyName= 'email'
grails.plugin.springsecurity.userLookup.passwordPropertyName= 'motDePasse'
but it doesn't work. I'm using grails 3.1.5, anyone can help me please?
the "Custom UserDetailsService" part of the documentation doesn't show how to replace attributes.
Thank you
I ended up with keeping the default password and replacing the username with email, I had simply to replace every "username" with "email" in the Person class:
package ma.ac.uir.ecine.authentification
import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString
#EqualsAndHashCode(includes='email')
#ToString(includes='email', includeNames=true, includePackage=false)
class Personne implements Serializable {
private static final long serialVersionUID = 1
transient springSecurityService
String email
String password
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
Personne(String email, String password) {
this()
this.email = email
this.password = password
}
Set<Role> getAuthorities() {
PersonneRole.findAllByPersonne(this)*.role
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
}
static transients = ['springSecurityService']
static constraints = {
password blank: false, password: true
email blank: false, unique: true
}
static mapping = {
password column: '`password`'
}
}
and add
grails.plugin.springsecurity.userLookup.usernamePropertyName= 'email'
to application.groovy
I couldn't replace the password.

Grails 3 + Spring Security Core Plugin Confirm Password

Hello today I've started to learn Grails 3 with Spring Security Core Plugin but I'm having hard time with password Validation. When user is registering I want him to type password and confirmPassword. Everything would be ok if not hashing the password. I want my password to be encoded in database but with encoding I'm not able to compare those 2 passwords.
Here is my class:
#EqualsAndHashCode(includes='username')
#ToString(includes='username', includeNames=true, includePackage=false)
class User implements Serializable {
private static final long serialVersionUID = 1
transient springSecurityService
String username
String password
String confirmPass
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
User(String username, String password) {
this()
this.username = username
this.password = password
this.confirmPass = password
}
Set<Role> getAuthorities() {
UserRole.findAllByUser(this)*.role
}
// because of that I can't compare password and confirmPass
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
}
static transients = ['springSecurityService']
static constraints = {
username blank: false, unique: true
password blank: false, size: 5..60, password: true, display: false, validator: { val, obj ->
if (!obj.id && !obj.password) {
return 'validation.user.password' // my message
}
}
confirmPass blank: // now I'm stuck here, I've tried isPasswordValid() but won't work cuz of 'salt' What shout go here?
}
static mapping = {
password column: '`password`'
}
}
What should I do to make it working(valid both password are same and then encoded password store in database).

Grails Scaffold hide table column

How I can hide password column from GORM view:
My domain class:
class SecUser {
static scaffold = true
transient springSecurityService
String username
String password
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
static transients = ['springSecurityService']
static constraints = {
username blank: false, unique: true
password (display:false, blank: false)
}
static mapping = {
password column: '`password`'
}
Set<SecRole> getAuthorities() {
SecUserSecRole.findAllBySecUser(this).collect { it.secRole } as Set
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
// password = password
}
}
The display: false constraint is used to hide the property from the default scaffolded view. The project at https://github.com/jeffbrown/scaffolddisplay demonstrates this. You must have something in your app that is getting in the way of that. Possibly you have generated views which contain the property. Possibly you are using a plugin which is providing the view.

How to get All users which have a certain Role in grails

I want to retrieve all users which have a specific Role like "ROLE_USER".
Below are Domain Classes for User, Role and UserRole.
User.groovy
class User {
transient springSecurityService
String username
String password
String email
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)
}
}
Role.groovy
class Role {
String authority
static mapping = {
cache true
}
static constraints = {
authority 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
}
}
These Domain Classes are generated by Spring Security plugin.
I have added only email field for User class.
Here is my UserController.groovy
class UserController {
def index = {
}
def list = {
def role = Role.findByAuthority("ROLE_USER")
println "role id "+role.id
def users = User.findAll() //Its giving me all Users regardless of Role
println "total users "+users.size()
for(user in users)
{
println "User "+user.username+" "+user.email
}
render (view: "listUsers", model:[users:users])
}
}
In the list action I used User.findAll() but its giving me all user with all roles.
I want user list only from a certain role..
EDIT
Code to Assign Roles to newly created user
def username = params.username
def emailID = params.emailID
def password = params.password
def testUser = new User(username: username, enabled: true, password: password,email:emailID)
testUser.save(flush: true)
def userRole = new Role(authority: 'ROLE_USER').save(flush: true)
UserRole.create testUser, userRole, true
Thanks..
Replace
def users = User.findAll()
with
def users = UserRole.findAllByRole(role).user
and you should get all users with the required role.
EDIT
In your code sample you try to create a new Role for the User. Since a Role with the authority ROLE_USER already exists and authority has to be unique (see the 'constraints' part in your Role class) this new Role cannot be saved to the database. Because the Role you assign in UserRole.create doesn't exist in the database the UserRole is not saved either. You would have to assign the existing Role to the new User (e.g. with `Role.findByAuthority').
Creating the roles in Bootstrap.groovy is a good idea according to Spring Source because roles "are typically defined early in the life of the application and correspond to unchanging reference data. That makes BootStrap the ideal place to create them." (Spring Source Blog)

Null Pointer on springSecurityService.currentUser when using weceem grails-plugin

i'm using Grails 2.1.1 in my project, right now i'm using springSecurityService.currentUser to get user credential, etc.
in the past 2 days, my project need some CMS extension and i've stumbled upon Weceem plugins.
set things here and there, in the end my project with Weceem plugins is now running, but getting Null Pointer Exception each time the springSecurityService.currentUser method is called.
Without weceem grails-plugin everything is running fine, so i assume there's some settings that i need to make. the question is where and what?
this is my user class
class User {
transient springSecurityService
String username
String password
boolean enabled = true
boolean accountExpired = false
boolean accountLocked = false
boolean passwordExpired = false
Person person
static hasOne = [Person]
static hasMany = [roles: Role]
static constraints = {
username blank: false, unique: true
password blank: false
}
static mapping = {
password column: '`password`'
}
Set<Role> getAuthorities() {
roles as Set
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}}
and this is my controller that called the springSecurityService
//show the list of all person
def list = {
//get all the sorting params
params.sort = params.sort ?: 'firstName'
params.order = params.order ?: 'asc'
params.max = params.max ?: 10
params.offset = params.offset ?: 0
def test = springSecurityService.getCurrentUser()
def personList = Person.createCriteria().list (max: params.max, offset: params.offset) {
if (springSecurityService.currentUser.person.affiliate.value != 'Admin'){
eq("affiliate", springSecurityService.currentUser.person.affiliate)
eq("deleted", false)
}
order(params.sort, params.order)
}
render view:'list', model:[persons: personList, personTotal: personList.totalCount]
}

Resources