spring中基于内存数据库的身份认证和角色授权示例分析
这篇文章主要介绍spring中基于内存数据库的身份认证和角色授权示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
一、引入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa 使用jpa进行持久化--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.1.7.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hsqldb/hsqldb 使用内存数据库--> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.5.0</version> </dependency>
二、新建相关文件
@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"); } List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 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<UserInfo,Long> { 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中基于内存数据库的身份认证和角色授权示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!