이제 DB를 이용해서 유저를 관리해 보자.
의존성 추가
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
엔티티 생성
@Entity
public class Account {
@Id @GeneratedValue
private Integer id;
@Column(unique = true)
private String username;
private String password;
private String role;
// ... getter, setter
}
레포지토리 생성
public interface AccountRepository extends JpaRepository<Account, Integer> {
}
중요한 서비스 생성
@Service
public class AccountService implements UserDetailsService {
private final AccountRepository accountRepository;
public AccountService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Account account = accountRepository.findByUsername(username);
if (account == null) {
throw new UsernameNotFoundException(username);
}
return User.builder()
.username(account.getUsername())
.password(account.getPassword())
.roles(account.getRole())
.build();
}
}
account 관련 서비스
db 연관된 일
UserDetailsService의 일을 하게 될것
username을 받아서 UserDetails 타입으로 리턴하는 일이 필요하다.
편하게 할 수 있도록 시큐리티가 User라는 클래스를 제공한다.