spring security 学习(二)用户认证自定义
spring security 学习(一)spring boot 中开启spring security 中介绍了spring boot开启security的简单实例 ,security会生成用户名和密码,项目开发中用户名和密码都是必须的,spring security 提供了自定义用户认证。
自定义认证需要重新实现userDetailService 接口,接口中有个方法 loadUserByUserName。
package org.springframework.security.core.userdetails; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; public interface UserDetailsService { UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException; }
UserDetails返回用户信息,也是一个接口。
package org.springframework.security.core.userdetails; import java.io.Serializable; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; public interface UserDetails extends Serializable {
//获取用户包含的权限,返回权限集合,权限是一个继承了
GrantedAuthority
的对象; Collection<? extends GrantedAuthority> getAuthorities(); //密码 String getPassword(); //用户名 String getUsername(); //是否已过期,已过期返回false;未过期返回true boolean isAccountNonExpired(); //是否未锁定,未锁定返回true,锁定返回false boolean isAccountNonLocked(); //判断密码是否过期 boolean isCredentialsNonExpired(); //判断用户是否可用 boolean isEnabled(); }
创建UserVoDetailsService 实现UserDetailsService;
@Configuration
public class UserVoDetailsService implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
//@Autowired
//private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 模拟一个用户,替代数据库获取逻辑
UserVo user = new UserVo();
user.setUserName(username);
user.setPassword(this.passwordEncoder.encode("123456"));
// 输出加密后的密码
System.out.println(user.getPassword());
return new User(username, user.getPassword(), user.isEnabled(),
user.isAccountNonExpired(), user.isCredentialsNonExpired(),
user.isAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}