본문 바로가기

스프링

[SpringBoot] PasswordEncoder 적용하기

오늘 간단히 회원가입로직을 짜면서 패스워드 암호화를 진행해보았다.

 

비밀번호 암호화 왜 필요할까? 

당연한걸 고민한다고 생각할지도 모른다. 비밀번호가 노출된다하더라도 서버에 중요한 정보가 없다면 문제가 안될수도 있다. 하지만 여러 웹사이트의 비밀번호를 동일하게 사용하는 유저라면 얘기가 달라진다. 한 사이트에서 비번이 유출된다면 이 사람이 가입된 모든 사이트가 해킹된 셈이다.

 

그래서 비밀번호 암호화를 해놓으면 서버가 해킹당해서 패스워드가 유출된다하더라도 해당 사용자의 이메일로 가입된 다른 웹사이트에는 접근할 수 없다. 또한 서버에서도 사용자의 비밀번호를 그대로 저장해서 책임질 일을 만들 필요가 없다. 

 

그래서 오늘은 스프링 시큐리티의 BCryptPasswordEncoder 정의와 사용법을 알아볼 예정이다.

 

BCryptPasswordEncoder란?

스프링 시큐리티는 자바 서버 개발을 위해 필요로 한 인증, 권한 부여 및 기타 보안 기능을 제공한다.

-BCryptPasswordEncoder는 BCrypt해싱함수를 사용해서 비밀번호를 인코딩해주는 메서드와 사용자에의해 제출된 비밀번호화 저장소에 저장되어있는 비밀번호의 일치 여부를 확인해주는 메서드를 제공한다.

- PasswordEncoder 인터페이스를 구현한 클래스

- 생성자의 인자 값(verstion, strength, SecureRandom instance)을 통해서 해시의 강도를 조절가능

 

BCrypt에 대한 설명

 

사용법

 

build.gradle 

dependencies{
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '2.4.5'
}

 

Config설정

springsecurity 환경설정을 진행해준다.

passwordEncoder를 빈으로 등록해주면, 어디에서든 @Autowired 어노테이션을 이용해서 가져올 수 있다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
   @Bean
   public PasswordEncoder getPasswordEncoder() {
      return new BCryptPasswordEncoder();
   }

   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http.cors().disable()
         .csrf().disable()
         .formLogin().disable()
         .headers().frameOptions().disable();
   }
}

 

적용

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
public class MemberService {

    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Transactional
    public void signUpUser(Member member) {
        member.setPassword(passwordEncoder.encode(member.getPassword()));
        memberRepository.save(member);
    }

 

참고

https://dkyou.tistory.com/61

https://youngjinmo.github.io/2021/05/passwordencoder/

'스프링' 카테고리의 다른 글

Annotation - @Entity  (0) 2022.03.09
Spring Bean  (0) 2022.02.20
스프링 삼각형과 설정 정보 - AOP / PSA  (0) 2022.02.09
의존성주입 DI(Dependency InJection)의 종류  (0) 2022.02.09
스프링  (0) 2022.02.09