본문 바로가기
Code/Web

[Spring Code] 암호화 처리를 이용한 회원가입과 로그인

by 스응 2023. 4. 22.
728x90
728x90

#  관련 포스팅

  - 암호화 처리 : https://young0105.tistory.com/238

 


#  WebMvcConfigurer 구현 클래스에 암호화 처리 인코더 선언

1
2
3
4
5
6
7
8
9
10
11
12
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
 
    // 암호화 처리 인코더
    // 이렇게 설정해두면 PasswordEncoder를 멤버 변수로 선언해서 사용 가능
    @Bean // IoC 관리 대상 처리
    public PasswordEncoder passwordEncoder() {
        
        return new BCryptPasswordEncoder();
    }
 
}
cs

  - 암호화 처리는 Service 레이어에서 수행

 

#  UserService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@Service // IoC 대상
public class UserService {
 
    // DAO 표준을 정의해둔 인터페이스
    @Autowired // 객체 생성 시 의존 주입 처리
    private UserRepository userRepository;
    
    // 암호화 처리 인코더
    @Autowired
    private PasswordEncoder passwordEncoder;
    
 
    @Transactional 
    public void createUser(SignUpFormDto signUpFormDto) {
 
        // 비밀번호 암호화 처리
        String rawPwd = signUpFormDto.getPassword();
        String hashPwd = passwordEncoder.encode(rawPwd);
        signUpFormDto.setPassword(hashPwd);
        
        // 암호화된 비밀번호를 DB에 저장
        int result = userRepository.insert(signUpFormDto);
        
        if (result != 1) {
            throw new CustomRestfullException("회원 가입에 실패했습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        
    }
    
    @Transactional
    public User signIn(SignInFormDto signInFormDto) {
        
        // username을 조건 컬럼으로 사용해서 사용자를 찾음
        User userEntity = userRepository.findByUsername(signInFormDto);
 
        // 검색 결과가 존재하지 않는다면
        if (userEntity == null) {
            throw new CustomRestfullException("존재하지 않는 username입니다.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        
        // username이 존재하는 경우에 대해서 비밀번호를 
        if (passwordEncoder.matches(signInFormDto.getPassword(), userEntity.getPassword()) == false) {
            throw new CustomRestfullException("비밀번호가 틀렸습니다.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        
        return userEntity;
    }
    
}
cs

 

320x100
반응형

댓글