gpt4 book ai didi

java - spring 登录失败后获取用户名

转载 作者:太空宇宙 更新时间:2023-11-04 12:29:17 25 4
gpt4 key购买 nike

我想生成在登录失败后(当帐户被禁用时)重新发送帐户激活 token 的网址。

我有 CustomAuthenticationFailureHandler:

  @Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
setDefaultFailureUrl("/login?error=true");
super.onAuthenticationFailure(request, response, exception);
Locale locale = localeResolver.resolveLocale(request);
String errorMessage = messages.getMessage("message.badCredentials", null, locale);

if (exception.getMessage().equalsIgnoreCase("User is disabled")) {
errorMessage = messages.getMessage("auth.message.disabled", null, locale);
} else if (exception.getMessage().equalsIgnoreCase("User account has expired")) {
errorMessage = messages.getMessage("auth.message.expired", null, locale);
}

request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, errorMessage);
}

我只在 View (jsp)中需要它,所以如果有办法从${SPRING_SECURITY_LAST_ATTEMPT.username}之类的东西中获取它,我会很高兴,但如果没有选项 - 如何将其从onAuthenticationFailure发送到模型?

最佳答案

首先我们创建一个自定义的authenticationProvider类。

@Component("authenticationProvider")
public class DisabledLoginAuthenticationProvider extends DaoAuthenticationProvider {

@Autowired
UserDetailsDao userDetailsDao;

@Autowired
@Qualifier("userDetailsService")
@Override
public void setUserDetailsService(UserDetailsService userDetailsService) {
super.setUserDetailsService(userDetailsService);
}

@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {

try {

Authentication auth = super.authenticate(authentication);

//if reach here, means login success, else an exception will be thrown
//reset the user_attempts

return auth;

} catch (DisabledException e){

//this user is disabled!
String error = "";

//this will db to check the no of attempts
UserAttempts userAttempts =
userDetailsDao.getUserAttempts(authentication.getName());

if(userAttempts!=null){
Date lastAttempts = userAttempts.getLastModified();
error = "User account is locked! <br><br>Username : "
+ authentication.getName() + "<br>Last Attempts : " + lastAttempts;
}else{
error = e.getMessage();
}

throw new LockedException(error);
}

}

}

然后在您的 Security xml 中附加您自定义的authenticationProvider。

<authentication-manager>
<authentication-provider ref="authenticationProvider"/>
</authentication-manager>

关于java - spring 登录失败后获取用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38020951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com