Following this approach, we can store the username in the HTTP session when a user is successfully authenticated. We can also check whether the user has been authenticated by checking whether a value exists in the HTTP session. This can be implemented as follows:
public class AuthService { private static final String USERNAME_ATTRIBUTE = "username"; public static boolean authenticate( String username, String password) { boolean authentic = "admin".equals(username) && "admin".equals(password); if (authentic) { VaadinSession.getCurrent().setAttribute( USERNAME_ATTRIBUTE, username); } return authentic; } public static boolean isAuthenticated() { return VaadinSession.getCurrent().getAttribute( USERNAME_ATTRIBUTE) != null; } }
There are a few things to notice here. First, for simplicity in this example, the code checks whether username and password are both equal to the string "admin". In a real application, this should query a database or delegate to any other authentication process. For example, if you have a class that provides functionality to query user data, the Boolean check could look something like the following:
User existingUser = userRepository.findByUsernameAndPassword( username, password); boolean authentic = existingUser != null;
user.setPassword(hash(theActualPassword));
In order to check whether a password is correct (for example, during authentication), you can compare the hash of the given password with the value stored in the database. Something like the following:
- String stored = user.getPassword();
- String hash = hash(attemptedPassword);
- if (stored.equals(hash) {...}
Second, the AuthService class has Vaadin stuff in it. Service classes should be decoupled from the presentation technology, but in our case, that's okay, since there's not much chance of us changing the web framework! And that's usually the case in real-life applications anyway. Additionally, reusing this class out of the context of a Vaadin application doesn't seem very likely, but if it becomes necessary, you can decouple it from Vaadin by directly using the HTTP session.