쌓고 쌓다

Spring Security 회원가입 및 BCrypt 본문

프로그래밍/spring

Spring Security 회원가입 및 BCrypt

승민아 2024. 1. 15. 15:38

 

BCrypt 는 단방향 암호화로 복호화가 불가능하다!

 

 

저장할 회원 테이블은 다음과 같다.

CREATE TABLE test_user (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255),
    password VARCHAR(255),
    role VARCHAR(255)
);

 

SecurityConfig

package com.example.spotserver.config;

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.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // 해당 메서드의 리턴되는 오브젝트를 IoC로 등록해준다.
    @Bean
    public BCryptPasswordEncoder encodePwd() {
        return new BCryptPasswordEncoder();
    }
    
    ...
}

 

 

BCryptPasswordEncoder를 빈으로 등록하지 않고 다음과 같이 DI를 한다면?

 

BCryptPasswordEncoder를 빈으로 등록하지 않는다면 다음과 같은 에러가 뜬다.

 

 

TestController

package com.example.spotserver.securityStudy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {


    private TestUserRepository testUserRepository;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    public IndexController(TestUserRepository testUserRepository, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.testUserRepository = testUserRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }
    
    ...
    
    @PostMapping("/join")
    public String join(TestUser testUser) {
        
        // 비밀번호를 암호화를 안한다면 시큐리티로 로그인할 수 없다.
        String rawPwd = testUser.getPassword();
        String encPwd = bCryptPasswordEncoder.encode(rawPwd);
        testUser.setPassword(encPwd);

        testUser.setRole("user");
        testUserRepository.save(testUser);
        return "redirect:/loginForm";
    }

}
  • encode() : form 태그를 통해 넘어온 비밀번호를 암호화 한다.

 

Comments