회원가입 구현 중 비밀번호 암호화 기능 추가하려고 한다.
우선 의존성 먼저 기입해준다.
build.grable에 추가
implementation 'org.springframework.boot:spring-boot-starter-security'
이후 LoginService.java 서비스로직에 비밀번호 암호화 후 set 해줄 거다.
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@RequiredArgsConstructor
@Service
public class LoginService {
private final LoginRepository loginRepository;
private final BCryptPasswordEncoder passwordEncoder;
// 비밀번호 암호화
String encryptedPassword = passwordEncoder.encode(loginEntity.getPassword());
loginEntity.setPassword(encryptedPassword); // 암호화된 비밀번호를 엔티티에 설정
// DB에 저장
return loginRepository.insert(loginEntity);
}
}
SecurityConfig.java 파일도 만들어준다.
public class SecurityConfig {
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
이후 서버를 실행시키니 아래와 같은 에러가 난다.
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of constructor in com.main.sub.PolishPix.Login.Service.LoginService required a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' in your configuration.
BCryptPasswordEncoder 메서드에 Bean 어노테이션을 추가해주면 된다.
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
그런데 security 의존성을 추가하니 계속 이런 로그인 창이 뜬다.
기존 Url을 입력해도 기본 로그인 페이지로 디라이렉팅된다.
SecurityConfig.java 를 수정해보자.
Spring Security가 HTTP 요청을 필터링할 때 사용하는 설정 체인에서 CSRF 비활성화하고 HTTP 요청에 대한 권한 설정을 해주면 된다.
즉, 전체 코드는 이렇다.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll()
);
return http.build();
}
}