티스토리 뷰

Project 댕린이집

비밀번호 암호화

xoo | 수진 2024. 3. 1. 20:54

WebSecurityConfig.java

 

PasswordEncoder를 빈으로 등록합니다.

	@Bean
	public PasswordEncoder passwordEncoder(){
		return new BCryptPasswordEncoder();
	}

 

PasswordEncoder는 주로 사용자의 비밀번호를 해싱(hashing)하여 저장하고, 로그인 시에 비밀번호를 검증하는 데 사용됩니다.

 

여기서 BCryptPasswordEncoderPasswordEncoder의 구현체 중 하나로, BCrypt 해싱 알고리즘을 사용하여 비밀번호를 안전하게 해싱합니다.

 


UserService.java

package com.example.demo.service;

import com.example.demo.dto.ResDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.example.demo.dto.UserDTO;
import com.example.demo.entity.UserEntity;
import com.example.demo.mapper.UserMapper;
import com.example.demo.repository.UserRepository;


@Service
public class UserService {
	
	@Autowired
	private UserRepository userRepository;

	@Autowired
	private PasswordEncoder passwordEncoder;

	// 아이디 중복 검사
	public Object idCheck(String userId) throws Exception {
		// 사용자 아이디가 빈 문자열인 경우 예외를 던짐
		if(userId.equals("")) {
			throw new Exception(); 
		}
		// UserRepository를 사용하여 주어진 사용자 아이디의 중복 여부를 확인
		return userRepository.existsByUserId(userId);
	}
	
	// 회원가입
	public ResDTO register(UserDTO userDTO) {
		// userDTO -> userEntity 로 변형하는 맵핑이 필요함.
		// mapper mapstruct

		if(userDTO.getUserId().equals("")) {
			return ResDTO.builder()
					.code("401")
					.message("비어있는 아이디")
					.data(false)
					.build();
		}

		UserEntity userEntity = UserMapper.instance.userDTOToUserEntity(userDTO);

		// 중복확인
			// 사용자 아이디가 빈 문자열인 경우 예외를 던짐

			// UserRepository를 사용하여 주어진 사용자 아이디의 중복 여부를 확인

		if(userRepository.existsByUserId(userEntity.getUserId())){
	 	// true -> 중복
		return ResDTO.builder()
				.code("400")
				.message("중복된 아이디")
				.data(false)
				.build();
		}

		userEntity.setPassword(passwordEncoder.encode(userDTO.getPassword()));

		return ResDTO.builder()
				.code("200")
				.message("회원가입 성공")
				.data(userRepository.save(userEntity))
				.build();
	}
	
}

 

@Autowired 애노테이션으로  PasswordEncoder를 주입받습니다.

 

그리고 회원가입 성공 시의 로직을 구현하는데요.

주어진 UserDTO 객체를 이용하여 UserEntity 객체를 생성하고, 비밀번호를 해싱하여 저장한 후, 이를 DB에 저장하고 성공적인 응답을 반환하게 됩니다.

 

자세히 살펴보겠습니다.

  • UserEntity userEntity = UserMapper.instance.userDTOToUserEntity(userDTO); 
    UserDTO 객체를 UserEntity 객체로 변환합니다. 이 작업은 DTO에서 Entity로의 변환을 담당하는 UserMapper 클래스의 userDTOToUserEntity 메서드를 사용합니다.
  • userEntity.setPassword(passwordEncoder.encode(userDTO.getPassword()));
    passwordEncoder 빈을 이용하여 userDTO에서 가져온 비밀번호를 안전하게 해싱하여 UserEntity 객체에 설정합니다.
  • return ResDTO.builder()...
    회원가입이 성공한 경우, HTTP 상태 코드 "200"과 함께 "회원가입 성공" 메시지를 담은 ResDTO 객체를 생성합니다. 또한, 데이터베이스에 저장된 userEntitydata 속성에 담아 반환합니다.

 


 

💻 결과

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
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
글 보관함