您好,登錄后才能下訂單哦!
這篇文章主要介紹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中基于內存數據庫的身份認證和角色授權示例分析”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。