inflearn logo
강의

講義

知識共有

Spring Boot Security & JWT講義

スプリングブート セキュリティ 第2講 - セキュリティ設定

주의! WebSecurityConfigurerAdapter deprecated

4573

kiwoong

投稿した質問数 16

15

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

강의에서 나온 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();
    }

     */
}

jwt Spring Security spring

回答 8

5

isdnhk

@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입니다

0

Tenacious

감사합니다

 

3

aossuper79113

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

authorizeHttpRequests() 쓰면 되고

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

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

1

jungmo19975195

줄 안생김

 

@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();
	}
}

 

0

seohyeonjin787

이렇게 하면 CsrfConfigurer를 찾을 수 없다고 나오는데 어떻게 해결하셨나요? ㅜㅜ

0

jungmo19975195

찾을 수 없다고나오는거면 임포트 문제일 가능성이 있을거 같네요

1

gil

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

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

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

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

1

kiwoong

저는 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

fkgnssla3487

감사합니다.

문제가 하나 있는데요.

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

0

dudgns12393860

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

0

adamku

안녕하세요! 

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

JWT를 구현한 다음 이 API를 호출해서 사용하는 것은 프론트엔드 쪽에서 하는 역할인가요?

0

96

1

Jwt쓰면 스프링시큐리티는 필수적으로 사용해야하나요?

0

401

1

13:23 system.out 출력문이 다르게 나옵니다.

0

130

1

수료증 문의

0

226

2

9분대에 질문이 있습니다 !

0

114

1

password 비교를 하지 않았는데 어떻게 인증이 통과된 건가요?

0

321

1

이전 강의 참고하라는 말씀

0

253

1

강의 실습하다가 막히는 분들 참고(2024년8월 기준)

2

1116

2

구글 소셜 로그인 302

0

200

1

오류 문의 _ org.springframework.orm.jpa.JpaSystemException: could not deserialize

1

584

1

[자바] 시큐리티 Config 참고

13

953

1

이론강의

0

280

1

SpringSecurity JWT 로그인 URL 2개 설정하는 방법

0

487

1

2024.06기준) 최근 SecurityConfig 설정 문의

0

921

3

구글 로그인시 authentication이 null 값이라고 에러가 발생합니다.

0

678

2

특정 url필터 거는 방법 이슈

0

422

1

강사님께서 말씀하시는 시큐리티세션이 SecurityContext인가요?

0

277

1

25강 마지막 테스트에서 오류

1

1044

2

jwt를 저장하는 위치에 궁금한 점이 있습니다.

0

298

1

mustache를 사용하지 않고 thymeleaf를 사용하려고 하는데

0

697

1

세션 인증방식이 REST 원칙에 위배되는 건가요?

0

340

1

jwt와 실제데이터의 관계

1

243

1

jwt 와 세션ID의 관계

1

313

1

SecurityConfig에서 세션 설정, 인가 설정

0

421

1