Java Spring在登录失败后获取用户名
我想生成的url将重新发送帐户激活令牌登录失败后(当帐户被禁用) 我有CustomAuthenticationFailureHandler:Java Spring在登录失败后获取用户名,java,spring,spring-mvc,spring-security,Java,Spring,Spring Mvc,Spring Security,我想生成的url将重新发送帐户激活令牌登录失败后(当帐户被禁用) 我有CustomAuthenticationFailureHandler: @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletExcepti
@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);
}
我只需要在视图(jsp)中使用它,所以如果有办法从诸如
${SPRING\u SECURITY\u LAST\u trunt.username}
之类的东西中查看它,我会很高兴。但是如果没有选项,那么如何将它从身份验证失败
发送到模型?首先我们创建一个定制的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);
}
}
}
@组件(“authenticationProvider”)
公共类DisabledLoginAuthenticationProvider扩展了DaoAuthenticationProvider{
@自动连线
UserDetailsDao UserDetailsDao;
@自动连线
@限定符(“userDetailsService”)
@凌驾
public void setUserDetailsService(UserDetailsService UserDetailsService){
super.setUserDetailsService(userDetailsService);
}
@凌驾
公共身份验证(身份验证)
抛出AuthenticationException{
试一试{
Authentication auth=super.authenticate(身份验证);
//如果到达此处,则表示登录成功,否则将引发异常
//重置用户尝试的次数
返回auth;
}捕获(禁用异常e){
//此用户已禁用!
字符串错误=”;
//这将使db检查尝试次数
用户尝试用户尝试=
userDetailsDao.getUserAttempts(authentication.getName());
if(userAttempts!=null){
Date lastAttempts=userAttempts.getLastModified();
error=“用户帐户已锁定!
用户名:”
+authentication.getName()+“
上次尝试:”+lastAttempts;
}否则{
错误=e.getMessage();
}
抛出新的LockedException(错误);
}
}
}
然后在安全xml中附加自定义的authenticationProvider
<authentication-manager>
<authentication-provider ref="authenticationProvider"/>
</authentication-manager>
第一步 在应用程序中添加spring安全性就是创建spring安全Java配置 例如:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
@Autowired
PersistentTokenRepository tokenRepository;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/list")
.access("hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')")
.antMatchers("/newuser/**", "/delete-user-*").access("hasRole('ADMIN')").antMatchers("/edit-user-*")
.access("hasRole('ADMIN') or hasRole('DBA')").and().formLogin().loginPage("/login")
.loginProcessingUrl("/login").usernameParameter("ssoId").passwordParameter("password").and()
.rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)
.tokenValiditySeconds(86400).and().csrf().and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Bean
public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices(
"remember-me", userDetailsService, tokenRepository);
return tokenBasedservice;
}
@Bean
public AuthenticationTrustResolver getAuthenticationTrustResolver() {
return new AuthenticationTrustResolverImpl();
}
}
第二步
PersistentTokenRepository的实现
例如:
安全配置中使用的UserDetailsService实现:
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
@Autowired
private UserService userService;
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String ssoId)
throws UsernameNotFoundException {
User user = userService.findBySSO(ssoId);
logger.info("User : {}", user);
if(user==null){
logger.info("User not found");
throw new UsernameNotFoundException("Username not found");
}
return new org.springframework.security.core.userdetails.User(user.getSsoId(), user.getPassword(),
true, true, true, true, getGrantedAuthorities(user));
}
private List<GrantedAuthority> getGrantedAuthorities(User user){
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for(UserProfile userProfile : user.getUserProfiles()){
logger.info("UserProfile : {}", userProfile);
authorities.add(new SimpleGrantedAuthority("ROLE_"+userProfile.getType()));
}
logger.info("authorities : {}", authorities);
return authorities;
}
}
感谢“记住我”的实现,但我已经做到了:)明天我会试试。谢谢你的回答。
@Entity
@Table(name="PERSISTENT_LOGINS")
public class PersistentLogin implements Serializable{
@Id
private String series;
@Column(name="USERNAME", unique=true, nullable=false)
private String username;
@Column(name="TOKEN", unique=true, nullable=false)
private String token;
@Temporal(TemporalType.TIMESTAMP)
private Date last_used;
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Date getLast_used() {
return last_used;
}
public void setLast_used(Date last_used) {
this.last_used = last_used;
}
}
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
@Autowired
private UserService userService;
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String ssoId)
throws UsernameNotFoundException {
User user = userService.findBySSO(ssoId);
logger.info("User : {}", user);
if(user==null){
logger.info("User not found");
throw new UsernameNotFoundException("Username not found");
}
return new org.springframework.security.core.userdetails.User(user.getSsoId(), user.getPassword(),
true, true, true, true, getGrantedAuthorities(user));
}
private List<GrantedAuthority> getGrantedAuthorities(User user){
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for(UserProfile userProfile : user.getUserProfiles()){
logger.info("UserProfile : {}", userProfile);
authorities.add(new SimpleGrantedAuthority("ROLE_"+userProfile.getType()));
}
logger.info("authorities : {}", authorities);
return authorities;
}
}
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}