spring security core grails not logging in - grails

Installed Spring Security Core as plugin then did quickstart
Here is my User domain class
package auth
class User {
def springSecurityService
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
static mapping = {
// password is a keyword in some sql dialects, so quote with backticks
// password is stored as 44-char base64 hashed value
password column: '`password`', length: 64
}
static constraints = {
username blank: false, size: 1..50, unique: true
password blank: false, size: 8..100
}
Set getAuthorities() {
UserRole.findAllByUser(this).collect { it.role } as Set
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected encodePassword() {
password = springSecurityService.encodePassword(password, username)
}
}
And my boostrap.groovy is
class BootStrap {
def init = { servletContext ->
auth.User james = new auth.User(username: 'test', enabled: true, password: 'password')
james.save()
if (james.hasErrors())
{
println("he has errors")
}
println("we made it! ")
}
def destroy = {
}
}
But when I go to login, it keeps saying "Sorry, we were not able to find a user with that username and password." Any thoughts?

This is because you are using the salt while encoding the password.
password = springSecurityService.encodePassword(password, username)
I have no idea of salting and hence can not guide you to much.
But if you encode your password without salting then your code works, just remove username when encoding the password, try this
password = springSecurityService.encodePassword(password)
Hope this helps.

If you create the user in BootStrap.groovy, try changing this:
def adminUser = User.findByUsername('admin') ?: new User(
username: 'admin',
password: springSecurityService.encodePassword('admin'),
enabled: true).save(failOnError: true)
to this:
def adminUser = User.findByUsername('admin') ?: new User(
username: 'admin',
password: 'admin',
enabled: true).save(failOnError: true)
The problem is that you are using the encoding password twice, once in the Domain and once in the constructor's parameters.

Can you validate that the user is actually bootstrapped into the database?
If so, I ran into a similar issue with Tomcat caching some data incorrectly.
Here is what I did:
Stopped Tomcat
Deleted all the files in Tomcat's Temp directory
Restarted Tomcat
After that, it worked fine.
Let me know if this helps.

Also, its been a while since I've built a Grails site from scratch, but I think I remember there being an issue with some online instructions. SpringSecurity might be encoding the password for you, so when you do it, it is getting double encoded.
Try removing the lines that encode the password.

Related

Grails 3 Spring Security UI Forgotten Password blank URL & user

I have customised grails.plugin.springsecurity.userLookup.usernamePropertyName = "email" but the default rendering behaviour for the email body will fail with:
No such property: username for class
Therefore I customised emailBody in my application.groovy:
grails.plugin.springsecurity.ui.forgotPassword.emailBody = "Dear ${user.email} , Please follow <a href='${url}'>this link</a> to reset your password. This link will expire shortly."
because according to the docs:
The emailBody property should be a GString and will have the User domain class instance in scope in the user variable, and the generated url to click to reset the password in the url variable.
However, the params map that contains the properties in my MailStrategy is empty for the user.email and url values:
[to:blah#blah.com,
from:no-reply#blah.com, subject:Reset your password for your account,
html:Dear [:], Please follow <a href='[:']>this link</a> to reset your password. This link will expire shortly.]
Notice the [:] and [:] for the user.email and url values.
The spring-security plugin is configured with these values in application.groovy:
grails.plugin.springsecurity.userLookup.userDomainClassName = 'blah.Account'
grails.plugin.springsecurity.userLookup.authorityJoinClassName = 'blah.AccountRole'
grails.plugin.springsecurity.authority.className = 'blah.Role'
grails.plugin.springsecurity.requestMap.className = 'blah.Requestmap'
grails.plugin.springsecurity.securityConfigType = 'Annotation'
The Account class is defined as:
String email
String password
Date emailVerified = null
boolean enabled = true
boolean accountExpired
boolean accountLocked
boolean passwordExpired
Set<Role> getAuthorities() {
AccountRole.findAllByAccount(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
emailVerified nullable: true
}
static mapping = {
password column: '`password`'
}
How can I have the username and more importantly the URL rendered for me so I can send the forgotten password email?
GString should start from " not from '
so instead of grails.plugin.springsecurity.ui.forgotPassword.emailBody = '...'
you should use: grails.plugin.springsecurity.ui.forgotPassword.emailBody = "..."

springSecurityService how to NOT store passwords in cleartext?

This tutorial:
http://spring.io/blog/2010/08/11/simplified-spring-security-with-grails/
Says you should create users like this:
def adminUser = SecUser.findByUsername('admin') ?: new SecUser(
username: 'admin',
password: springSecurityService.encodePassword('admin'),
enabled: true).save(failOnError: true)
However, this does not work. It only works if you do this:
password: 'admin'
Which I am assuming (but could be wrong) that stores the password in the internal DB in plain text (not hashed).
Is there a way to tell spring to encrypt or hash passwords? Its not in any of the tutorials, and can't find it in the manual
Grails 2.3.6, security core 2.0-RC2 & UI, default install.
I have seen it said that grails by default does hash with bcrypt, but I dont know how to verify this. I guess I need to install mysql, tell grails to use this, then I can query the values.
Take a deep breath. By default the spring security plugin for Grails (recent versions) isn't going to store you passwords in clear text.
Take a look at your SecUser domain class and you will see that it's handling the encryption of the password for you. You can also see an example of this in the documentation.
This is directly from the documentation.
package com.mycompany.myapp
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)
}
}
If you haven't already read through the documentation I suggest you do. It's well written and will likely answer a lot of other questions you have about the plugin.

Grails domain class constraint modification causing exception

Am using grails 2.0.3 with default h2 database and have the following user domain class:
class User {
transient springSecurityService
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
Preferences preferences
Company company
Personal personal
static constraints = {
username email: true, blank: false, unique: true
password blank: false
preferences unique: true
company unique: true
personal unique: true
}
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)
}
}
In the controller, I save the user using the following code:
userInstance.save(flush: true)
Now, this afternoon, I realized that the password field should have a size constraint and hence modified the domain class so that it became as follows (only change is in the constraints):
class User {
transient springSecurityService
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
Preferences preferences
Company company
Personal personal
static constraints = {
username email: true, blank: false, unique: true
password blank: false, size: 6..15
preferences unique: true
company unique: true
personal unique: true
}
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)
}
}
Subsequently I generated the views and controllers again. Now when I am trying to save the user object from the controller, using:
userInstance.save(flush: true)
I am getting the following exception:
Class: org.hibernate.AssertionFailure
Message: null id in login.User entry (don't flush the Session after an exception occurs)
Any help will be appreciated.
Info: If I remove the size constraint from the new/modified class the
saving happens fine.
I ran into the same problem using Grails 3.1.12. This is what I found out and how I solved it.
Problem:
You are trying to put a size constraint to a field that is going to be enconded. This means that a password like "admin5" will turn at the end of the domain life cycle as an encoded pwd. For example the db will stored the pwd as: "$2a$10$dn7MyN.nsU8l05fMkL/rfek/d1odko9H4QUpiNp8USGhqx9g0R6om".
The validation process will apply the size constraint to the unencoded pwd (validation step on the domain life cycle), wich will pass because the pwd typed by the user is in that range. but on the save() method (persistance step on the domain life cycle) the pwd will be encoded before an insert or update. The enconding method will create a pwd with a size bigger than your constraint and Hibernate will fail the assert() for the pwd size.
Solution:
Use the minSize constraint if you don't need to worry about the maxSize
static constraints = {
password blank: false, minSize:6
}
If you need to validate the maxSize, then I recommend you do the validation on your Service or Controller layer before creating the domain instance.

Grails Spring-Security-Core plugin - Cannot authenticate user

So I am banging my head against the wall trying to get spring-security-core-1.2.7.1 to work with Grails 2.0...
I have looked at the tutorial and run s2. Read that the new plugin encrypts passwords for you, so my bootstrap looks like:
def userRole = Role.findByAuthority('ROLE_USER') ?: new Role(authority: 'ROLE_USER').save(failOnError: true)
def adminRole = Role.findByAuthority('ROLE_ADMIN') ?: new Role(authority: 'ROLE_ADMIN').save(failOnError: true)
def adminUser = User.findByUsername('admin') ?: new User(
username: 'admin',
password: "admin",
enabled: true).save(failOnError: true)
def testUser = User.findByUsername('test') ?: new User(
username: 'test',
password: "test",
enabled: true).save(failOnError: true)
if (!adminUser.authorities.contains(adminRole)) {
UserRole.create adminUser, adminRole
}
if (!testUser.authorities.contains(userRole)) {
UserRole.create testUser, userRole
}
I can look at the H2 database and I see the users, their encoded passwords, see that the roles are created and can see the user role mappings are properly created as well.
However, I still get "Sorry, we were not able to find a user with that username and password." at the login prompt for both users.
I have turned on log4j debug 'org.springframework.security' but all I really get out of the logs is:
2012-01-23 23:08:44,875 ["http-bio-8080"-exec-5] DEBUG dao.DaoAuthenticationProvider - Authentication failed: password does not match stored value
I can't see anything obviously wrong with your code. I'm using the same version of Grails and the spring security plugin, and the following code in Bootstrap.groovy works for me:
def init = { servletContext ->
// create some roles
def userRole = createRole('ROLE_USER')
def adminRole = createRole('ROLE_ADMIN')
// create some users
User admin = createUser('Admin', 'admin#mailinator.com', adminRole)
User user = createUser('User', 'user#yahoo.co.uk', userRole)
}
private User createUser(name, username, role) {
def defaultPassword = 'password'
User user = User.findByUsername(username) ?: new User(
name: name,
username: username,
password: defaultPassword,
passwordConfirm: defaultPassword,
enabled: true).save()
if (!user.authorities.contains(role)) {
UserRole.create user, role
}
user
}
private createRole(String roleName) {
Role.findByAuthority(roleName) ?: new Role(authority: roleName).save()
}
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.
You can fix the multiple datasources issue by updating the User class.
See https://stackoverflow.com/q/13296594
In the OP's original code, why is the username in single quotes and the password in double quotes. That might be the problem.

Bcrypt generates different hashes for the same input?

I just added a registration functionality to my new grails project. For testing it, I registered by giving an email and a password. I am using bcrypt algorithm for hashing the password before saving it to the database.
However when I try to login with the same email and password that I gave while registering, login fails. I debugged the application and found out that the hash that is generated for the same password is different when I try to compare with the already hashed one from database and hence the login is failing (Registration.findByEmailAndPassword(params.email,hashPassd) in LoginController.groovy returns null).
Here's my domain class Registration.groovy:
class Registration {
transient springSecurityService
String fullName
String password
String email
static constraints = {
fullName(blank:false)
password(blank:false, password:true)
email(blank:false, email:true, unique:true)
}
def beforeInsert = {
encodePassword()
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
}
Here's my LoginController.groovy:
class LoginController {
/**
* Dependency injection for the springSecurityService.
*/
def springSecurityService
def index = {
if (springSecurityService.isLoggedIn()) {
render(view: "../homepage")
}
else {
render(view: "../index")
}
}
/**
* Show the login page.
*/
def handleLogin = {
if (springSecurityService.isLoggedIn()) {
render(view: "../homepage")
return
}
def hashPassd = springSecurityService.encodePassword(params.password)
// Find the username
def user = Registration.findByEmailAndPassword(params.email,hashPassd)
if (!user) {
flash.message = "User not found for email: ${params.email}"
render(view: "../index")
return
} else {
session.user = user
render(view: "../homepage")
}
}
}
Here's a snippet from my Config.groovy telling grails to use bcrypt algorithm to hash passwords and the number of rounds of keying:
grails.plugins.springsecurity.password.algorithm = 'bcrypt'
grails.plugins.springsecurity.password.bcrypt.logrounds = 16
Jan is correct - bcrypt by design doesn't generate the same hash for each input string. But there's a way to check that a hashed password is valid, and it's incorporated into the associated password encoder. So add a dependency injection for the passwordEncoder bean in your controller (def passwordEncoder) and change the lookup to
def handleLogin = {
if (springSecurityService.isLoggedIn()) {
render(view: "../homepage")
return
}
def user = Registration.findByEmail(params.email)
if (user && !passwordEncoder.isPasswordValid(user.password, params.password, null)) {
user = null
}
if (!user) {
flash.message = "User not found for email: ${params.email}"
render(view: "../index")
return
}
session.user = user
render(view: "../homepage")
}
Note that you don't encode the password for the isPasswordValid call - pass in the cleartext submitted password.
Also - completely unrelated - it's a bad idea to store the user in the session. The auth principal is readily available and stores the user id to make it easy to reload the user as needed (e.g. User.get(springSecurityService.principal.id). Storing disconnected potentially large Hibernate objects works great in dev mode when you're the only user of your server, but can be a significant waste of memory and forces you to work around the objects being disconnected (e.g. having to use merge, etc.).
A BCrypt hash includes salt and as a result this algorithm returns different hashes for the same input. Allow me to demonstrate it in Ruby.
> require 'bcrypt'
> p = BCrypt::Password.create "foobar"
=> "$2a$10$DopJPvHidYqWVKq.Sdcy5eTF82MvG1btPO.81NUtb/4XjiZa7ctQS"
> r = BCrypt::Password.create "foobar"
=> "$2a$10$FTHN0Dechb/IiQuyeEwxaOCSdBss1KcC5fBKDKsj85adOYTLOPQf6"
> p == "foobar"
=> true
> r == "foobar"
=> true
Consequently, BCrypt cannot be used for finding users in the way presented in your example. An alternative unambiguous field should be used instead, e.g. user's name or e-mail address.

Resources