我创建了一个自定义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;
}
}
SsoAuthenticationProvider
检查:
问题是并非所有这些异常都会被堆叠到控制器上,所以似乎无法通知用户登录问题。
使用UserDetails
等isEnabled()
等方法并不可能,因为我们不同用户帐户状态的语义完全不同。
这是使用自定义异常构建自定义安全性的正确方法吗?我应该实施其他方法来使这项工作吗?
答案 0 :(得分:4)
要结束之前提出的问题,让我解释一下我们做了什么。 正如我对之前的响应所评论的那样,在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;
}
所有异常都是spring安全异常堆栈的一部分。也就是说,这些自定义异常继承自某些现有异常。然后,在安全控制器中,您应检查安全性异常并根据需要对其进行处理。例如,重定向到不同的页面。
希望这有帮助!
答案 1 :(得分:2)
我认为最好使用user detail对象的其他方法/属性来实现此目的。 像
isAccountNonExpired()
isAccountNonLocked()
isEnabled()
如果要显示自定义错误消息,请按照此article
中的说明使用消息属性