在Spring Security中使用自定义异常

Dan*_*edo 5 java spring-security

我创建了一个自定义AuthenticationProvider来执行自定义安全检查.我还创建了继承的自定义异常,AccountStatusException以通知用户状态问题,例如用户在特定时间段内未验证其帐户的UserDetails情况.我也是自定义实现.

这是我执行的安全检查的代码.省略了与案例无关的代码.

public class SsoAuthenticationProvider implements AuthenticationProvider {

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        User user = null;
        if (username != null) {
            user = getUserRepository().findByUserName(username);
            if (user != null) {
                if (user.getEnabled() != 0) {
                    if ((user.getUserDetail().getConfirmed() != 0)
                            || ((new Date().getTime() - user.getUserDetail().getRequestDate().getTime()) / (1000 * 60 * 60 * 24)) <= getUnconfirmedDays()) {
                        if (getPasswordEncoder().isPasswordValid(user.getPassword(),
                                (String) authentication.getCredentials(), user)) {
                            user.authenticated = true;
                            user.getAuthorities();
                        }
                    } else {
                        throw new UserNotConfirmedAndTimeExceeded(
                                "User has not been cofirmed in the established time period");
                    }
                } else {
                    throw new DisabledException("User is disabled");
                }
            } else {
                throw new BadCredentialsException("User or password incorrect");
            }
        } else {
            throw new AuthenticationCredentialsNotFoundException("No credentials found in context");
        }
        return user;
    }
}
Run Code Online (Sandbox Code Playgroud)

SsoAuthenticationProvider检查:

  1. 用户名已注册(存在于数据库中)
  2. 用户已确认他的电子邮件
  3. 如果用户尚未确认他的电子邮件,请检查他是否仍处于宽限期内(这​​是我们让用户在允许他们访问网站时确认其电子邮件的几天)
  4. 如果用户尚未确认电子邮件且他未处于宽限期内,请抛出安全例外以表示这些状态并拒绝身份验证

问题是并非所有这些异常都会被堆叠到控制器上,因此似乎无法通知用户登录问题.

使用UserDetails诸如isEnabled()(和类似)之类的方法是不可能的,因为我们不同用户帐户状态的语义完全不同.

这是使用自定义异常构建自定义安全性的正确方法吗?我应该实施其他方法来使这项工作?

Dan*_*edo 6

为了结束之前提出的问题,让我解释一下我们做了什么。正如我对之前的回复所评论的那样,在 UserDetails 对象中使用提供的方法是不可行的,因为您无法使用给定的方法捕获所有登录失败语义。在我们的例子中,这些语义仍然非常有限,但在其他情况下,它可以随着时间的推移无限扩展以表达不同的用户情况。异常方法最终是最好的方法。最终的代码看起来像这样

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username=(String)authentication.getPrincipal();
    User user=null;
    if(username!=null){
        user=getUserRepository().findByUserName(username);
        if(user!=null){
            if(user.getEnabled()!=0){
                if((user.getUserDetail().getConfirmed()!=0)||((new Date().getTime()-user.getUserDetail().getRequestDate().getTime())/(1000 * 60 * 60 * 24))<=getUnconfirmedDays()){
                    if(getPasswordEncoder().isPasswordValid(user.getPassword(), (String)authentication.getCredentials(), user)){
                        user.authenticated=true;
                        user.getAuthorities();
                    } else {
                        throw new BadCredentialsException("Password incorrect");
                    }
                }else{
                    throw new UserNotConfirmedAndTimeExceeded("User has not been cofirmed in the established time period");         
                }
            }else{
                throw new DisabledException("User is disabled");
            }
        }else{
            throw new BadCredentialsException("User does not exist");
        }
    }else{
        throw new AuthenticationCredentialsNotFoundException("No credentials found in context");
    }
    return user;
}
Run Code Online (Sandbox Code Playgroud)

所有异常都是 spring 安全异常堆栈的一部分。也就是说,那些自定义异常继承自一些现有的异常。然后,在您的安全控制器中,您应该检查安全异常并根据需要处理它们。例如重定向到不同的页面。

希望这可以帮助!