如何添加有关用户未经过身份验证的原因的详细信息?

时间:2015-09-07 13:51:42

标签: java spring authentication error-handling spring-security

我们为用户添加了属性isBlocked

如果设置了以下属性,则用户无法在我们的网站上登录。

我们想要呈现错误消息"your account is temporary blocked..."

但是我没有想法如何将此消息传递给loginFailed控制器方法。

我有以下spring-security配置:

public class XXXSecurityServiceImpl implements UserDetailsService {

    @Autowired
    private TerminalAdminDao terminalAdminDao;

    @Override
public UserDetails loadUserByUsername(String adminName) throws UsernameNotFoundException,
        DataAccessException {
    TerminalAdmin admin = terminalAdminDao.findAdminByEmail(adminName);
    UserDetails userDetails = null;
    if (admin != null) {
        Set<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
        for (AdminRole adminRole : admin.getAdminRoles()) {
            authorities.add(new SimpleGrantedAuthority(adminRole.getRole()));
        }
        userDetails = new User(admin.getEmail(), admin.getPassword(), true, true, true, !admin.isBlocked(),
                authorities);
    }
    return userDetails;
}

管理员失败的受控方法:

@RequestMapping(value = "/loginAdminFailed", method = RequestMethod.GET)
public String loginError(HttpSession session) {
    session.setAttribute("login_error", "true");
    return "admin/login";
}

如何在控制器中理解用户被阻止?

2 个答案:

答案 0 :(得分:0)

基本上,您需要注册自定义身份验证提供程序和自定义身份验证失败处理程序来处理身份验证异常。

检查此SO问题。

答案 1 :(得分:0)

这有效

添加到控制器:

    @RequestMapping(value = "/loginAdminFailed", method = RequestMethod.GET)
    public String loginError(HttpSession session, HttpServletRequest request) {
        session.setAttribute("message", getErrorMessage(request, "SPRING_SECURITY_LAST_EXCEPTION"));
        return "admin/login";
    }
    // customize the error message
    private String getErrorMessage(HttpServletRequest request, String key) {
        Exception exception = (Exception) request.getSession().getAttribute(key);
        String error = "";
        if (exception instanceof BadCredentialsException) {
            error = messageSource.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.badCredentials", null, LOCALE_RU);
        } else if (exception instanceof LockedException) {
            error = messageSource.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.accountIsLocked", null, LOCALE_RU);
        } else {
            error = messageSource.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.badCredentials", null, LOCALE_RU);
        }

        return error;
    }

但这看起来很难看