Spring Security 이용 - 회원가입

·2023년 6월 6일
0

토이프로젝트

목록 보기
2/2

이제 회원가입을 추가할 때가 왔다.
Spring Security 는 따로 배워본적이 없어서 여기에서 많이 도움을 받았다.

구글링을 하면 나오는 SecurityConfig 설정 파일은 5.X 버전이 많은데, 최신 업데이트된 버전은 6.1 버전이라 설정 파일 문법이 약간 달라졌다.

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests().requestMatchers(
                new AntPathRequestMatcher("/**")).permitAll()
                ;
        return http.build();
    }
}

찾아보면 위와 같은 구성의 코드들이 많은데, 쓰는 방법이 달라졌다.
구글링 해도 내가 못찾는 건지 많은 답변들이 나오진 않고, 유일하게 찾은 스오플 답변에서 방법을 발견했다.

return http.csrf(csrf -> csrf.disable())
                .authorizeRequests(auth -> auth
                                .requestMatchers("/user/**").authenticated()
                                .anyRequest().permitAll()
                )).build();

그래서 이런 방식으로 고치면 사용이 가능하다.
공식문서 찾아보면 다른 옵션들도 사용하는 법이 나온다.

'csrf()' is deprecated and marked for removal
'authorizeHttpRequests()' is deprecated and marked for removal
이런 오류가 자꾸 뜬다면 위와 같이 고치면 해결이 된다.


SecurityConfig 파일을 생성했다면 그 다음에는 domain, repositary, memberForm, controller 에 약간의 수정이 필요하다.
JPA 수업을 통해 아주 간단한 회원가입 양식은 구현해두었으니 거기에 스프링 시큐리티만 살짝 추가하면 된다.

Member 추가

    private String password;

    @Column(unique = true)
    private String email;

MemberRepositary 추가

member.setPassword(passwordEncoder.encode(member.getPassword()));

여기서 passwordEncoder는 보안을 위해 암호화한 비밀번호로 저장하게 만드는 것인데,
repositary에 BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); 방식으로 객체를 new로 생성하는 방식보다는

SecurityConfig 파일에 PasswordEncoder 빈(bean)으로 등록하는게 추후 암호화 방식을 변경할 것을 생각하면 더 좋다. 나중에 암호화 방식을 변경하게 될 때 BCryptPasswordEncoder를 사용한 모든 프로그램을 일일이 찾아서 수정해야 하기 때문에!

따라서 SecurityConfig 파일에도 passwordEncoder 함수를 추가해준다.

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

마지막으로 controller의 create 함수와 memberForm.class, memberForm.html에 새롭게 추가된 password, email 컬럼을 추가해주면 spring security를 이용한 회원가입 생성이 완료된다.

마지막 행에 이렇게 암호화된 패스워드로 잘 들어온 것을 볼 수 있다.

0개의 댓글