I have implemented spring security to protect sections of our website. I am using a DB (MongoDB) to store username/password. I implemented org.springframework.security.core.userdetails.UserDetailsService to lookup the account details from the DB.
I still need to add another feature: account activation. After registration, we send an activation email to a user and if he clicks on it, we mark the account as activated in the DB. Users that have not activated their account, should not be allowed to log in and should be redirected to a page for that.
Any ideas on how to implement? I need to somehow hook into the login process.
Thanks!
Custom AuthenticationManager is not needed. This feature is already available in Spring Security. Take a look to the doc, you can see the enabled
property. When you create the user, if you set that property to false and user try to login, Spring will display automatically a message informing the user that account is not active.
UPDATED
In order to display Spring error messages, you should use this in the login page:
<c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
You can create custom authentication manager where you can check if the user is activated or not
<bean id="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"
p:authenticationManager-ref="customAuthenticationManager"
p:authenticationFailureHandler-ref="customAuthenticationFailureHandler"
p:authenticationSuccessHandler-ref="customAuthenticationSuccessHandler" />
and custom authenticationManager
<bean id="customAuthenticationManager"
class="com.mycompany.security.CustomAuthenticationManager" />
CustomAuthenticationManager.java
public class CustomAuthenticationManager implements import org.springframework.security.authentication.AuthenticationManager{
@Override
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
User user = null;
if (auth.getName() == null) {
throw new BadCredentialsException("User does not exists!");
}
user = userService.getUserByUsername(auth.getName());
if (user == null) {
throw new BadCredentialsException("User does not exists!");
}
if (passwordEncoder.isPasswordValid(user.getPassword(), (String) auth.getCredentials(), null)) {
//check if user is activated if not throw appropriate excetion
} else {
throw new BadCredentialsException("User does not exists!");
}
}
and it will redirect user back to login page (if configured properly)
now in login.jsp, get the failure reason by
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
and show the appropriate message to user }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With