커스텀 필터 적용 안됨
961
5 asked
강의를 다 수강하고 깃허브 코드 참조하여 작성했습니다.
현재 SecurityConfig 코드는 다음과 같습니다.
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig{
private final UserRepository userRepository;
private final CorsConfig corsConfig;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement((sessionManagement) ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.formLogin(withDefaults())
.httpBasic(withDefaults())
.apply(new MyCustomDsl())
.and()
.authorizeRequests(requests -> requests
.requestMatchers("/user/**").authenticated()
.requestMatchers("/admin/**").access("hasAuthority('ADMIN')")
.anyRequest().permitAll()
)
.build();
}
public class MyCustomDsl extends AbstractHttpConfigurer<MyCustomDsl, HttpSecurity> {
@Override
public void configure(HttpSecurity http) throws Exception {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
http
.addFilter(corsConfig.corsFilter())
.addFilter(new JwtAuthenticationFilter(authenticationManager))
.addFilter(new JwtAuthorizationFilter(authenticationManager, userRepository));
}
}
}
filterchain에서 and()에 오류가 발생합니다.
'and()' is deprecated and marked for removal
로 나오는데 and가 deprecated된 거 같지는 않고 커스텀 필터를 적용하는 것에서 뭔가 문제가 있지 않을까 싶습니다만 이틀째 해결을 못하고 있어 문의남깁니다ㅠㅠ
Answer 1
0
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
return http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement((sessionManagement) ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.formLogin(withDefaults())
.httpBasic(withDefaults())
.addFilter(corsConfig.corsFilter())
.addFilter(new JwtAuthenticationFilter(authenticationManager))
.addFilter(new JwtAuthorizationFilter(authenticationManager, userRepository))
.authorizeRequests(requests -> requests
.requestMatchers("/user/**").authenticated()
.requestMatchers("/admin/**").access("hasAuthority('ADMIN')")
.anyRequest().permitAll()
)
.build();
}커스텀 필터를 적용 안하고 커스텀 필터에 코드를 filterchain에 작성하면 어떨까 싶어
위와 같이 작성해보았었으나, 빨간 줄은 안 뜨지만 디버깅해보니 authenticationManager가 null이라고 나왔었습니다..
0
제 깃헙에 브랜치가 총 3개 있어요!! 여기서 소스코드 보고 작성하시면 되요
0
늦었지만 제 해결 사례를 알려드리자면,,
http 객체에 쭉 이어서 붙이지 마시고 and() 부분에서 한번 끊고 다시 연결시니까 해결이 되었습니다
http.csrf(cs-> cs.disable())
.sessionManagement(s->s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.formLogin(f->f.disable())
.httpBasic(h->h.disable())
.apply(new MyCustomDs1()); // custom Filter
//.addFilter(new JWTAuthenticationFilter(authenticationManager))
//.addFilter(new JWTAuthorizationFilter(authenticationManager, userRepository))
http.authorizeHttpRequests(authorize-> { // 권한 부여
// authorizeRequests가 deprecated됨에 따라 authorizeHttpRequests 사용 권장
authorize
.requestMatchers("/user/**").hasAnyRole("hasRole('ROLE_USER') or hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')")
.requestMatchers("/manager/**").hasAnyRole("hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')")
.requestMatchers(("/admin/**")).hasAnyRole("hasRole('ROLE_ADMIN')")
// .requestMatchers("/user/**").hasAnyAuthority("USER","MANAGER","ADMIN")
// .requestMatchers("/user/**").authenticated()
// .requestMatchers("/manager/**").hasAnyAuthority("MANAGER", "ADMIN")
// .requestMatchers("/manager/**").access("hasAuthority('ROLE_ADMIN')")
// .requestMatchers(("/admin/**")).hasAuthority("ADMIN")
.anyRequest().permitAll(); // 이외의 요청은 모두 허용함
});
/* Spring Security 사용 시
http.formLogin(f->f{
f.loginProcessingUrl("/login"); // 로그인 url 설정
});
*/
// /user, /manager, /admin으로 들어가도 /loginForm으로 접근하도록
return http.build();
}
JWT를 구현한 다음 이 API를 호출해서 사용하는 것은 프론트엔드 쪽에서 하는 역할인가요?
0
94
1
Jwt쓰면 스프링시큐리티는 필수적으로 사용해야하나요?
0
401
1
13:23 system.out 출력문이 다르게 나옵니다.
0
129
1
수료증 문의
0
226
2
9분대에 질문이 있습니다 !
0
114
1
password 비교를 하지 않았는데 어떻게 인증이 통과된 건가요?
0
320
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
486
1
2024.06기준) 최근 SecurityConfig 설정 문의
0
921
3
구글 로그인시 authentication이 null 값이라고 에러가 발생합니다.
0
677
2
특정 url필터 거는 방법 이슈
0
422
1
강사님께서 말씀하시는 시큐리티세션이 SecurityContext인가요?
0
277
1
25강 마지막 테스트에서 오류
1
1044
2
jwt를 저장하는 위치에 궁금한 점이 있습니다.
0
298
1
mustache를 사용하지 않고 thymeleaf를 사용하려고 하는데
0
694
1
세션 인증방식이 REST 원칙에 위배되는 건가요?
0
336
1
jwt와 실제데이터의 관계
1
241
1
jwt 와 세션ID의 관계
1
310
1
SecurityConfig에서 세션 설정, 인가 설정
0
415
1

