Monday, October 09, 2006

EJB3 Entity Callbacks for Password Fields

After about an hour of pounding my head over how I can automatically encode a stored password after it has been modified I came up with what I think is a pretty clever solution (though hopefully not the best, let me know if you know a better one that doesn't involve stored procedures!):

@Entity
public class Member {
Integer id;
String username;
String password;
...
transient boolean hasPasswordChanged;

@PrePersist void beforeInsert() {
if( hasPasswordChanged ) {
password = encode( password );
hasPasswordChanged = false;
}
}
public void setPassword(String password) {
hasPasswordChanged = true;
this.password = password;
}
...
}

The function tagged with the PrePersist annotation is called before the entity manager persists an entity to the data source. This is the ideal time to perform operations like this. The 'transient' field simply means that the value will not be serialized or persisted to the database.

1 comments:

Diwant Vaidya said...

This is still the best way I have found of storing a hashed password with EJB3. Is this still what you would suggest?

What about a @Password annotation? Or an @Encrypted?

Thanks,
Diwant