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๋ฅผ ๋ณด๊ณ  ์ž‘์„ฑํ•œ ๊ธ€์ž…๋‹ˆ๋‹ค.