I have an entity class User
that contains information such as username, first name, last name and a password and I have my GlassFish 3.1 server setup to perform authentication. So far, so good. After the container has authenticated a user, I need some way to bind the principal to the actual User entity. After all, GlassFish is telling me is that user "laurens" has authenticated, it is not giving me the corresponding User
entity.
To that end I wrote a JSF managed bean UserController
. What I would like to know is if this is the correct way to look the actual entity up and if there are any obvious pitfalls I am not seeing.
UserController
features the following fields:
@EJB
private UserFacade userFacade;
private User user;
The userFacade
is a stateless session bean to persist and find User
instances. The user
field is used by the JSF page to get and set properties on the user.
I use the following method to perform the binding accompanied by two helper methods:
@PostConstruct
private void init() {
try {
user = userFacade.find(getUserPrincipal().getName());
} catch (NullPointerException ex) {
// Intentionally left empty -- User is not logged in.
}
}
private HttpServletRequest getHttpServletRequest() {
return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
}
private Principal getUserPrincipal() {
return getHttpServletRequest().getUserPrincipal();
}
The following methods are used by the JSF page to determine what components to show (if the user is already authenticated then there is no need to show a login form), authenticate the user if the "Login" button is clicked, or register as a new user when the "Register" button is clicked.
public boolean isAuthenticated() {
return getUserPrincipal() != null;
}
public void authenticate() {
try {
getHttpServletRequest().login(user.getEmailAddress(), user.getPassword());
} catch (Exception ex) {
// TODO: Handle failed login attempt
}
}
public void register() {
userFacade.create(user);
}
Would this the correct way to go about?
Thanks!
Edit:
Thanks for the input both! I thought about it for a bit, and while I think moving the passwords to a different table is a little to much for me to handle at the moment, I do think I can address some of the issues by separating the UserController
in a @RequestScoped
AuthenticationController
and a stripped down @SessionScoped
UserController
.
The AuthenticationController
would have emailAddress
and password
fields, bound by the web page's emailAddress and password fields. It would additionally contain the public void authenticate()
to authenticate the user and discard the credentials afterwards. The @SessionScoped
UserController
can then bind to the appropriate User
entity without ever needing to know a password. In fact I believe I would be able to remove the password field from User
altogether.