[스프링] SecurityConfig

모선·2024년 4월 9일

spring

목록 보기
3/5

교재를 통해서 WebSecurityConfig 로직을 작성하고 있었는데 deprecated since version 6.1 and marked for removal 라는 오류문을 만나 구글링과 GPT를 통해 코드를 수정해봤습니다.

글로 정리해보면서 코드를 이해하고 정리해보는 시간을 갖고자 합니다.

http 요청에 대한 웹 보안

인증&인가, 로그인, 로그아웃에 대한 설정을 합니다.

기존 코드

	@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        return http
                .authorizeRequests() // 인증 & 인가 설정
                .requestMatchers("/", "/login", "/join", "/user").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin() // 폼 기반 로그인
                .loginPage("/login")
                .defaultSuccessUrl("/")
                .and()
                .logout() // 로그아웃
                .logoutSuccessUrl("/login")
                .invalidateHttpSession(true)
                .and()
                .csrf().disable() // csrf 비활성화 (실습의 편의성을 위함)
                .build();
    }

수정 코드

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        return http
                .csrf((csrfConfig) -> csrfConfig.disable())
                .authorizeRequests((requests) -> requests
                        .requestMatchers("/", "/login", "/join", "/user").permitAll()
                        .anyRequest().authenticated()
                )
                .formLogin((form) -> form
                        .loginPage("/login")
                        .defaultSuccessUrl("/", true).permitAll()
                )
                .logout((logout) -> logout
                        .logoutSuccessUrl("/login")
                        .invalidateHttpSession(true)
                )
                .build();
    }

6.1 버전부터는 위 코드를 lambda식으로 변형으로 사용하도록 하고 있습니다.

method

  • requestMatchers() : 특정 요청과 일치하는 url에 대한 엑세스를 설정

  • permitAll() : 특정 url로 요청이 오면 인증/인가 없이도 누구나 접근 가능

  • anyRequest() : requestMatchers()에서 설정한 url 이외의 요청에 대한 설정

  • authenticated() : 인가는 필요없지만, 인증을 성공해야만 접근 가능

  • loginPage() : 로그인 페이지 경로

  • defaultSuccessUrl() : 로그인 후 이동할 경로

  • logoutSuccessUrl() : 로그아웃 후 이동할 경로

  • invalidateHttpSession() : 로그아웃 후 세션을 전체 삭제할지의 여부

인증 관리자 설정

사용자 정보를 가져오는 service를 재정의하거나, 인증 방법을 설정할 때 사용합니다.

기존 코드

	@Bean
    public AuthenticationManager authenticationManager(HttpSecurity http, BCryptPasswordEncoder bCryptPasswordEncoder, UserDetailService userDetailService) throws Exception {
        return http
        		.getShareObject(AuthenticationManagerBuilder.class)
                .userDetailsService(userService)
                .passwordEncoder(bCryptPasswordEncoder);
                .and()
                .build();
    }

and().build()가 6.1 버전부터는 사라진다면서 오류가 났습니다.

수정 코드

	@Bean
    public AuthenticationManager authenticationManager(HttpSecurity http, BCryptPasswordEncoder bCryptPasswordEncoder, UserDetailService userDetailService) throws Exception {
        AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class);
        builder.userDetailsService(userService)
                .passwordEncoder(bCryptPasswordEncoder);
        
        return builder.build();
    }

사실 이렇게 바꾸는 게 맞는지 모르겠어요... 계속 알아봐야...할 것 같습니다......

method

  • userDetailsService() : 사용자 정보를 가져올 service. 반드시 UserDetailsService를 상속 받은 클래스여야 합니다.
  • passwordEncoder() : 비밀번호 암호화 인코더 설정

password 인코더 빈 등록

	@Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

Reference

스프링 부트 3 백엔드 개발자 되기(자바 편)

코드가 너무 다양해서 혼자 해결하기 너무너무 어렵네여,,
스프링 더 공부해서 돌아오겠습니다 , , ,,

profile
https://hy5sun.tistory.com/ << 이사중

0개의 댓글