十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
这篇文章主要介绍spring中基于内存数据库的身份认证和角色授权示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
成都创新互联从2013年开始,先为松阳等服务建站,松阳等地企业,进行企业商务咨询服务。为松阳企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
一、引入依赖
org.springframework.boot spring-boot-starter-data-jpa 2.1.7.RELEASE org.hsqldb hsqldb 2.5.0
二、新建相关文件
@Component public class CustomUserDetailService implements UserDetailsService { @Autowired private UserInfoService userInfoService; @Autowired private PasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { /* 1 通过username获取到userInfo信息 2 通过User(username,password,authorities)返回UserDetails */ UserInfo userInfo = userInfoService.findByusername(username); if(userInfo == null ) { throw new UsernameNotFoundException("NOT FOUND"); } Listauthorities = new ArrayList (); authorities.add(new SimpleGrantedAuthority("ROLE_"+userInfo.getRole().name())); User userDetails = new User(userInfo.getUsername(),passwordEncoder.encode(userInfo.getPassword()),authorities); return userDetails; } }
/** * 用户实体类,主要存储用户的登录名和密码 */ @Entity //持久化配置 public class UserInfo { @Id @GeneratedValue private long uid; //主键 private String username; //用户名 private String password; //密码 @Enumerated(EnumType.STRING) private Role role; public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public enum Role { admin,normal } public long getUid() { return uid; } public void setUid(long uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
@Service public class DataInit { @Autowired private UserInfoRepository userInfoRepository; @PostConstruct public void dataInit(){ UserInfo admin = new UserInfo(); admin.setUsername("admin"); admin.setPassword("000000"); admin.setRole(UserInfo.Role.admin); userInfoRepository.save(admin); } }
public interface UserInfoRepository extends JpaRepository{ public UserInfo findByusername(String username); }
@Service public class UserInfoServiceImpl implements UserInfoService { @Autowired private UserInfoRepository userInfoRepository; @Override public UserInfo findByusername(String username) { return userInfoRepository.findByusername(username); } }
public interface UserInfoService { public UserInfo findByusername(String username); }
以上是“spring中基于内存数据库的身份认证和角色授权示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!