• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

주의! WebSecurityConfigurerAdapter deprecated

22.08.18 11:50 작성 조회수 3.56k

14

안녕하세요 저같은 초보자분들이 계실까봐 여기 적어놓습니다ㅎㅎ

강의에서 나온 WebSecurityConfigurerAdapter가 현재 2022년에는 deprecated되었네요...ㅜ

그래서 저도 약간 해매었는데요..

처음 공부할 때는 그래도 데이터쌓는개념이고, 각자의 인내심을 해당 프레임워크에 익숙하게 하는데도

바쁠 것같아 코드 올려 놓습니다ㅎㅎ 참고하세요!

 

@Configuration
@EnableWebSecurity //스프링 시큐리티 필터가 스프링 필터체인에 등록 (스프링 필터 사용해봣쥬?)
public class SecurityConfig{

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .antMatchers("/manager/**").access("hasAnyRole('ROLE_MANAGER','ROLE_ADMIN')")
                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                .anyRequest().permitAll();

        return http.build();
    }

    /*
    기존: WebSecurityConfigurerAdapter를 상속하고 configure매소드를 오버라이딩하여 설정하는 방법
    => 현재: SecurityFilterChain을 리턴하는 메소드를 빈에 등록하는 방식(컴포넌트 방식으로 컨테이너가 관리)
    //https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

    @Override
    protected void configure(HttpSecurity http) throws  Exception{
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/user/**").authenticated()
                .antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")
                .antMatchers("/admin").access("\"hasRole('ROLE_ADMIN')")
                .anyRequest().permitAll();
    }

     */
}

답변 8

·

답변을 작성해보세요.

4

isdnhk님의 프로필

isdnhk

2023.10.03

@Configuration
@EnableWebSecurity //스프링 시큐리티 필터가 스프링 필터체인에 등록된다.
public class SecurityConfig{

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(CsrfConfigurer::disable);
        http.authorizeHttpRequests(authorize ->
                authorize
                        .requestMatchers("/user/**").authenticated()
                        .requestMatchers("/manager/**").hasAnyRole("ADMIN", "MANAGER")
                        .requestMatchers("/admin/**").hasAnyRole("ADMIN")
                       
                        .anyRequest().permitAll()
        );

        return http.build();
    }
}

security 6.1입니다

Tenacious님의 프로필

Tenacious

2023.12.28

감사합니다

 

2

authorizeRequests() 쓰지말라고 밑줄 나오시는분들

authorizeHttpRequests() 쓰면 되고

antMatchers() 대신에 requestMatchers() 쓰면 됩니다

access() 대신에 hasAnyRole() 쓰면 됩니당

1

정정모님의 프로필

정정모

2024.01.17

줄 안생김

 

@Configuration
@EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록된다.
public class SecurityConfig {

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http.csrf(CsrfConfigurer::disable);
//		http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
		http.sessionManagement((sessionManagement) -> 
								sessionManagement
									.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
//		http.formLogin().disable();
		http.formLogin((form)->
						form.disable());
//		http.httpBasic().disable();
		http.httpBasic((basic)->
						basic.disable());
		http.authorizeHttpRequests(authorize -> authorize.requestMatchers("/user/**").authenticated()
				.requestMatchers("/manager/**").hasAnyRole("ADMIN", "MANAGER")
				.requestMatchers("/admin/**")
				.hasAnyRole("ADMIN").anyRequest().permitAll());

		return http.build();
	}
}

 

1

gil님의 프로필

gil

2022.09.06

저도 보고서 정리하고 공유하려고 했는데 이미 작성이 되어있군요 ㅎㅎ

제가 참고한 글도 남겨드립니다.

이렇게 바로 솔루션 확인하는 것 보다 찾아보고 이해하고 직접 적용하는게 기억에 더 많이 남는거 같아요

https://blog.naver.com/PostView.naver?blogId=h850415&logNo=222755455272&parentCategoryNo=&categoryNo=37&viewDate=&isShowPopularPosts=true&from=search

1

저는 AuthenticationManager라는 인터페이스를 CustomAuthenticationManager라는 클래스로 구현하여 주었어요. 그리고 해당 클래스를 빈에 등록하여 주고 SecurityConfig에 의존성을 주입하여 주었답니다.

@Component
@RequiredArgsConstructor
public class CustomAuthenticationManager implements AuthenticationManager {

    private final CustomBCryptPasswordEncoder bCryptPasswordEncoder;
    private final PrincipalDetailsService principalDetailsService;

    //출처:https://stackoverflow.com/questions/71281032/spring-security-exposing-authenticationmanager-without-websecurityconfigureradap
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        PrincipalDetails principalDetails = (PrincipalDetails) principalDetailsService.loadUserByUsername(authentication.getName());

        if(!bCryptPasswordEncoder.matches(authentication.getCredentials().toString(), principalDetails.getPassword())){
           throw new BadCredentialsException("Wrong password!");
        }
        
        return new UsernamePasswordAuthenticationToken(principalDetails, null, principalDetails.getAuthorities());
    }

0

김형민님의 프로필

김형민

2023.01.05

감사합니다.

문제가 하나 있는데요.

localhost:8080/logout 호출 시 로그아웃이 되어야 하는데 login이 출력됩니다. 시큐리티가 낚아채서 로그아웃이 되야하는 것 아닌가요? 작성자님 코드를 갖다쓰긴 했는데 저만 안 되나 싶어서 여쭤봅니다,, ㅠㅠ

0

영훈님의 프로필

영훈

2022.10.22

감사합니다 감사합니다 감사합니다..

0

adamku님의 프로필

adamku

2022.08.22

안녕하세요! 

혹시 JwtAuthenticationFilter 필터 추가와 AuthenticationManager 빈은 어떻게 해결하셨을까요?