Spring Security登录:用户必须在登录前激活他们的帐户

时间:2012-06-25 10:24:04

标签: java spring security authentication

我已实施spring security以保护我们网站的各个部分。我使用DB(MongoDB)来存储用户名/密码。我实现了org.springframework.security.core.userdetails.UserDetailsS​​ervice来从数据库中查找帐户详细信息。

我仍然需要添加其他功能:帐户激活。注册后,我们会向用户发送激活电子邮件,如果他点击它,我们会在DB中将该帐户标记为已激活。未激活其帐户的用户不应该被允许登录,应该被重定向到该页面。

关于如何实施的任何想法?我需要以某种方式挂钩登录过程。

谢谢!

2 个答案:

答案 0 :(得分:10)

不需要自定义AuthenticationManager 。 Spring Security中已提供此功能。看一下doc,您可以看到enabled属性。创建用户时,如果将该属性设置为false并且用户尝试登录,则Spring将自动显示一条消息,通知用户该帐户未处于活动状态。

<强>已更新

为了显示Spring错误消息,您应该在登录页面中使用它:

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

答案 1 :(得分:2)

您可以创建自定义身份验证管理器,以便检查用户是否已激活

<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}

并向用户显示相应的消息 }