해쉬

해쉬로 암호화한다는 것은 고정길이의 문자값으로 변경한다는 것이다. 

안녕  ▷ AFB239DF

안녕! ▷ KGL48872

 

해쉬화를 이용해 비밀번호를 DB에는 알아볼 수 없는 암호화가 변경되어 들어가도록 하자

 

 

 

해쉬 테스트할때는 csrf를 비활성화 해준다.

 

[SecurityConfig] 

@Override​
protected void configure(HttpSecurity http) throws Exception {
	http
		.csrf().disable() // csrf 토큰 비활성화 (테스트시 걸어두는 게 좋음)

 

왜?

방어방법 중 csrf 토큰을 사용하면 모든요청을 검증하고 외부의 공격을 막아주는데 

우리는 form태그로 회원가입을 들고오는게 아니라 자바스크립트로 요청했고

csrf토근이 없기때문에 시큐리티가 기본적으로 막았다

그래서 테스트할때는 .csrf().disable()  csrf를 비활성화 하여 막지 않게하고 테스트를 하는것이다. 

 

 

 

해쉬 특징

로그인할때 시큐리티가 지켜보다가 username, password 두 정보를 가로챈다

그 다음 로그인을 진행시키고 로그인 완료가 되면 시큐리티 세션에 유저정보를 저장하고 관리한다.(loC)

그리고 유저정보를 필요할때마다 가져와 쓴다(가져오는 방식이 'DI')

 

시큐리티 세션에 있는 유저정보 객체는 타입이 정해져있다 type : userDetails 

원래 내가 만든 user 오브젝트 extends userDetails 를하여 유저정보를 저장해준다. 

 

 

 

비밀번호 해쉬화 하는방법 

 

[SecurityConfig]

@Bean   // loC가 된다. 함수가 리턴하는 값(BCryptPasswordEncoder)을 스프링이 관리한다.
public BCryptPasswordEncoder encodePWD() {    // 시큐리티가 들고있는 함수
    return new BCryptPasswordEncoder();
}

 encodePWD() 함수를 호출할 시 BCryptPasswordEncoder 객체를 리턴받을 수 있다. 

 

어떻게?

new BCryptPasswordEncoder().encode("1234"); 를 해주면 1234 를 암호화해준다.

 

 

 

 

[UserApiController]

 

회원가입할때 /auth/joinProc 

@RestController //데이터만 리턴
public class UserApiController {

@Autowired
private UserService userService// DI 하기

@PostMapping("/auth/joinProc")
public ResponseDto<Integer> save(@RequestBody User user) { // 직접 받는건 username, password, email
    System.out.println("UserApiController : save 호출됨");
    int result = userService.회원가입(user);
    return new ResponseDto<Integer>(HttpStatus.OK.value(), result);
  }
}

 

 

[UserService]

@Service
public class UserService {

  @Autowired
  private UserRepository userRepository;

  @Autowired
  private BCryptPasswordEncoder encoder;

  @Transactional
  public int 회원가입(User user) {
      try {
      String rawPassword = user.getPassword();                       // 1234 원문
      String encPassword = encoder.encode(rawPassword);   // 해쉬
       user.setPassword(encPassword);
        
       user.setRole(RoleType.USER)
       userRepository.save(user);
          return 1;
      } catch (Exception e) {
          e.printStackTrace();
          System.out.println("UserService : 회원가입() : " + e.getMessage());
      }
      return -1;
   }
}

String rawPassword = user.getPassword(); 패스워드를 가져와서 encoder.encode(rawPassword) 해쉬화를 하여 user.setPassword(encPassword); user객체에 넣어준다.

 

 

DB에 password 가 암호화돼서 들어갔음

 

 

 

 

반응형
LIST

+ Recent posts