Spring Security Login with a Twist: Users Must Activate Their Account Before Logging In

I implemented spring protection to protect sections of our website. I am using DB (MongoDB) to store username / password. I implemented org.springframework.security.core.userdetails.UserDetailsService to search for account information from the database.

I still need to add another feature: account activation. After registration, we send an email to the activation user, and if he clicks on it, we mark the account as activated in the database. Users who have not activated their account are not allowed to log in and must be redirected to the page.

Any ideas on how to implement? I need to somehow connect to the login process.

Thank!

+5
source share
2 answers

A custom AuthenticationManager is not needed . This feature is already available in Spring Security. Take a look at the doc , you can see the property enabled. When you create a user, if you set this property to false and the user tries to log in, Spring will automatically display a message informing the user that this account is inactive.

UPDATED

To display Spring error messages, you should use this on the login page:

<c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
+9
source

, ,

<bean id="authenticationFilter"     class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"
        p:authenticationManager-ref="customAuthenticationManager"
        p:authenticationFailureHandler-ref="customAuthenticationFailureHandler"
        p:authenticationSuccessHandler-ref="customAuthenticationSuccessHandler" />

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!");
        }

    }

( )

login.jsp,

${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}

}

+2

All Articles