Spring
[Spring] Spring Security(์คํ๋ง ์ํ๋ฆฌํฐ) ์ฌ์ฉ์ DB ๋ฑ๋ก ๋ฐ PasswordEncoder
DAHLIA CHOI
2023. 11. 22. 20:13
Form ์ธ์ฆ - PasswordEncoder
๋น๋ฐ๋ฒํธ๋ฅผ ์์ ํ๊ฒ ์ํธํํ๋๋ก ์ ๊ณต
์์ฑ
- PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder()
- ์ฌ๋ฌ ๊ฐ์ PasswordEncoder ์ ํ์ ์ ์ธํ ๋ค, ์ํฉ์ ๋ง๊ฒ ์ ํํด์ ์ฌ์ฉํ ์ ์๋๋ก ์ง์ํ๋ Encoder์ด๋ค.
์ํธํ ํฌ๋งท
- {id}encodedPassword
- ๊ธฐ๋ณธ ํฌ๋งท์ Bcrypt : {bcrypt}$2a@10~~~
- ์๊ณ ๋ฆฌ์ฆ ์ข ๋ฅ : bcrypt, noop, pbkdf2, scrypt, sha256
PasswordEncoder๋ฅผ ์ด์ฉํด ๋น๋ฐ๋ฒํธ ์ํธํ๋ฅผ ํ ๋ค ์ฌ์ฉ์๋ฅผ ์ ์ฅํ๊ณ ์ถ๋ค๋ฉด!
์๋์ ๊ฐ์ด ํ๋ฉด ๋๋ค. (ํ์ง๋ง ์๋๋ ๊ฐ์๋ฅผ ๋ณด๊ณ ์ฝ๊ฒ ์ด๋ก ์ ์ตํ๋ฉฐ ๋ฐ๋ผํ ๊ฑฐ๊ณ ํ๋ก์ ํธ์์๋ ์ด๋ ๊ฒ ์ฌ์ฉํ์ง ์์๋ค ใ ใ )
SecurityConfig
@Bean
public static PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
PasswordEncoder๋ฅผ ๋น์ผ๋ก ๋ฑ๋กํด ์ค๋ค.
UserService
public interface UserService {
void createUser(Account account);
}
UserServiceImpl
@Service
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
@Builder
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional
public void createUser(Account account) {
userRepository.save(account);
}
}
service์ serviceImp์ ๋๋๋ ์ด์ ๋ ์ถ์ํ๋ฅผ ์ํด์ ๋ง๋๋ ๊ฒ์ผ๋ก ์๊ณ ์๋๋ฐ ์ ์ ๋งํ๋ฏ์ด ๊ตณ์ด ์ฌ์ด๋ ํ๋ก์ ํธ์์๋ ๋๋ ํ์๊ฐ ์๋ ๊ฒ ๊ฐ๋ค. ์ด์ฐจํผ ๋ณดํต์ ์๋น์ค๋ ํ ์ญํ ๋ง ๋ด๋นํ๊ณ ์๊ณ ํ์ฅ์ํฌ ๋งํผ์ ํฐ ํ๋ก์ ํธ๋ฅผ ์งํํ ์ผ์ด ์๋ค๊ณ ์๊ฐ..
UserController
@GetMapping("/users")
public String createUser() {
return "user/login/register";
}
@PostMapping("/users")
public String createUser(AccountDto accountDto) {
ModelMapper modelMapper = new ModelMapper();
Account account = modelMapper.map(accountDto, Account.class); //dto๋ฅผ account ์ํฐํฐ์ ๋งคํ์์ผ์ฃผ๋ ์ญํ
account.setPassword(passwordEncoder.encode(account.getPassword()));
userService.createUser(account);
return "redirect:/";
}
UserRepository
public interface UserRepository extends JpaRepository<Account, Long> {
}
ํด๋น ๊ธ์ ์ธํ๋ฐ์ ์คํ๋ง์ํ๋ฆฌํฐ-Spring Boot ๊ธฐ๋ฐ์ผ๋ก ๊ฐ๋ฐํ๋ Spring Security๋ฅผ ๋ณด๊ณ ์์ฑํ ๊ธ์ ๋๋ค.