Reputation: 908
Im using grails for web development and spring security for authentication and authorization.
I want to make a simple form to allow users to change their password. This is a form with three password fields. The first is supposed for the current (old) password. The second and third are for the new password with validation to prevent accidental wrong typing.
The problem is that I cant figure out the proper way to validate the old password against the current one. I thought about doing it manually by using the springSecurityService.encodePassword
function and comparing the hashes. But I am not sure if this is the correct way of doing it.
This form is only accessible for users which are already logged in. Asking for the password should stop an attacker from changing the password if they somehow got hold of the session (user forgot to log out for example)
Is there a spring security way to do this?
Upvotes: 3
Views: 4819
Reputation: 31
This is what I'm using in Grails 2.3 and spring-security-core-2.0-RC4.
import com.example.User
import grails.plugin.springsecurity.SpringSecurityService
class UserController {
SpringSecurityService springSecurityService
def checkUserPasswordMatches(){
//Get current user
User user = springSecurityService.getCurrentUser()
String currentPassword = params.password
if (!springSecurityService.passwordEncoder.isPasswordValid(user.getPassword(), currentPassword, null)) {
log.info("INFO - Password does not match!"
//TODO: Do something now passwords match...
} else {
log.info("INFO - Password matches existing user password!"
//TODO: Do something after passwords mismatch...
}
}
}
Upvotes: 3
Reputation: 1
That's how it served me and I validate the confirmation of the new password.
def cambio= {
def respuesta = [error: 1]
SecUser user = springSecurityService.currentUser
if (params?.j_password && params?.password && params?.old_password) {
String oldPasword=params?.old_password
String newPassword = params.j_password
String newPassword2 = params.password
if (!springSecurityService.passwordEncoder.isPasswordValid(user.getPassword(), oldPasword, null)) {
respuesta.error=3
render respuesta as JSON
}else if(newPassword == newPassword2) {
user.setPassword(params.j_password)
user.save()
respuesta.error=0
render respuesta as JSON
}else
{
respuesta.error=2
render respuesta as JSON
}
}else{
render respuesta as JSON
}
}`
Upvotes: 0
Reputation:
There's an example in the Spring Security Core docs that uses passwordEnconder
, but springSecurityService.encodePassword
is fine too.
Upvotes: 3