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检查:
问题是并非所有这些异常都会被堆叠到控制器上,因此似乎无法通知用户登录问题.
使用UserDetails诸如isEnabled()(和类似)之类的方法是不可能的,因为我们不同用户帐户状态的语义完全不同.
这是使用自定义异常构建自定义安全性的正确方法吗?我应该实施其他方法来使这项工作?
为了结束之前提出的问题,让我解释一下我们做了什么。正如我对之前的回复所评论的那样,在 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 安全异常堆栈的一部分。也就是说,那些自定义异常继承自一些现有的异常。然后,在您的安全控制器中,您应该检查安全异常并根据需要处理它们。例如重定向到不同的页面。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
14428 次 |
| 最近记录: |