本文共 1718 字,大约阅读时间需要 5 分钟。
在Spring Security中,用户的校验逻辑是不需要自己是实现的。但是我们需要通过页面用户输入的信息和数据库的用户信息进行比较。
Spring Security中提供了一个 接口UserDetailsService, 在他的loadUserByUsername方法中,对从数据库获取的用户信息进行封装。
自定义实现UserDetailsService
@Componentpublic class MyUserDetailService implements UserDetailsService { private static final Logger logger = LoggerFactory.getLogger(MyUserDetailService.class); // 需要使用Spring Security提供的密码加密类,不然会报错。 // 可以实现该接口,自定义密码加密类。 @Autowired private PasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { logger.info("用户给名:{}", username); // 从数据库获取用户信息 String password = passwordEncoder.encode("123456"); return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); }}在这里插入代码片
在这里需要使用 Spring Security的加密类,PasswordEncoder。
PasswordEncoder有两个方法,
encode方法供 加密时使用。
matches方法,供spring Security进行密码校验时使用。
public interface PasswordEncoder { String encode(CharSequence var1); boolean matches(CharSequence var1, String var2); default boolean upgradeEncoding(String encodedPassword) { return false; }}
在返回UserDetails时,可以设置对用户的账号使用情况进行校验。
boolean isAccountNonExpired(); 账号是否过期boolean isAccountNonLocked(); 账号是否冻结boolean isCredentialsNonExpired(); 凭证是否过期boolean isEnabled(); 账号是否可用
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { logger.info("用户给名:{}", username); // 从数据库获取用户信息 String password = passwordEncoder.encode("123456"); // 根据数据信息进行判断账号使用情况 return new User(username, password, true, true, true, true,AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); }```
转载地址:http://wdfoi.baihongyu.com/