java 用户进行锁定_Java中SpringSecurity密码错误5次锁定用户的实现方法

Spring Security简介

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

下面看下实例代码:

第一步:创建 AuthenticationSuccessEventListener.Java 用来处理登录成功的事件。

package com.dcits.yft.auth;

import com.dcits.yft.system.dao.UserDao;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationListener;

import org.springframework.security.authentication.event.AuthenticationSuccessEvent;

import org.springframework.stereotype.Component;

import java.util.Map;

/**

* 登陆成功监听

*

* @author Shaoj 3/2/2017.

*/

@Component

public class AuthenticationSuccessEventListener implements ApplicationListener {

@Autowired

private UserDao userDao;

@Override

public void onApplicationEvent(AuthenticationSuccessEvent authenticationSuccessEvent) {

YftUserDetails yftUserDetails = (YftUserDetails) authenticationSuccessEvent.getAuthentication().getPrincipal();

String account = yftUserDetails.getUsername();

Map user = userDao.queryUserByAccount(account);

userDao.updateStatusByAccount(account, user.get("ENABLE").toString(), 0);

}

}

第二步:新建AuthenticationFailureListener.java 用来处理登录失败的事件。

package com.dcits.yft.auth;

import com.dcits.yft.system.dao.ParamsDao;

import com.dcits.yft.system.dao.UserDao;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationListener;

import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;

import org.springframework.stereotype.Component;

import java.util.Map;

/**

* 登陆失败监听

*

* @author Shaoj 3/2/2017.

*/

@Component

public class AuthenticationFailureListener implements ApplicationListener {

@Autowired

private UserDao userDao;

@Autowired

private ParamsDao paramsDao;

@Override

public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent authenticationFailureBadCredentialsEvent) {

String account = authenticationFailureBadCredentialsEvent.getAuthentication().getPrincipal().toString();

Map user = userDao.queryUserByAccount(account);

if (user != null) {

// 用户失败次数

int fails = Integer.parseInt(user.get("FAILS").toString());

fails++;

// 系统配置失败次数

int FAILS_COUNT = Integer.parseInt(paramsDao.queryParamsValue("FAILS_COUNT"));

// 超出失败次数,停用账户

if (fails >= FAILS_COUNT) {

userDao.updateStatusByAccount(account, "false", fails);

// 失败次数++

} else {

userDao.updateStatusByAccount(account, user.get("ENABLE").toString(), fails);

}

}

}

}

第三步:在UserDao.java中加入登录状态更新的代码

/**

* 更新用户登录次数

*

* @param account 账户

* @param login_counts 登录次数

* @return

*/

public void updateLoginCounts(String account) {

daoUtil.update("update t_yft_user set login_counts = login_counts + 1 where account = ?", account);

}

第四步:数据库中添加登录次数字段

alter table T_YFT_USER add (FAILS number(11) default 0 );

comment on column T_YFT_USER.FAILS is '失败尝试次数';

[sql] view plain copy

INSERT INTO t_yft_params (ID,CODE,NAME,VALUE,UNIT,REMARK,CRT_DATE)

VALUES (66,'FAILS_COUNT','登陆尝试次数','5','','',to_date('2017-03-02','yyyy-mm-dd'));

以上所述是小编给大家介绍的Java中SpringSecurity密码错误5次锁定用户的实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对聚米学院网站的支持!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security,可以通过配置账户锁定来增强安全性。当用户连续输入错误密码时,可以将其账户锁定一段时间,以防止恶意攻击。具体实现方式如下: 1. 在数据库添加一个字段用于记录账户是否被锁定。 2. 在Spring Security的配置文件添加如下代码: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("ADMIN", "USER") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .permitAll() .and() .logout() .permitAll() .and() .rememberMe() .key("uniqueAndSecret") .tokenValiditySeconds(86400) .and() .exceptionHandling().accessDeniedPage("/403") .and() .csrf().disable(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 3. 在UserDetailsService的实现添加如下代码: ``` @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found"); } if (user.isLocked()) { throw new LockedException("User account is locked"); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, !user.isLocked(), AuthorityUtils.createAuthorityList(user.getRole())); } } ``` 在上述代码,如果用户锁定,则会抛出LockedException异常,从而阻止用户登录。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值