-
카테고리
-
세부 분야
백엔드
-
해결 여부
미해결
JWT - 24강 authenticationManager() 문제 해결책
24.01.18 15:42 작성 조회수 550
2
버전 문제로 authenticationManager() 안되면
SecurityConfig
@Configuration
@RequiredArgsConstructor
@EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록된다.
public class SecurityConfig {
private final CorsConfig corsConfig; //
private final CorsFilter corsFilter; // Bean 으로 등록되어 있어서 바로 가져다 써도됨 근데 나는 걍 위에 클래스에서 메소드 호출할거임~
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
// http.addFilterBefore(new MyFilter3(), SecurityContextHolderFilter.class);
http.csrf(CsrfConfigurer::disable);
// http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.sessionManagement((sessionManagement) ->
sessionManagement
.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
http.addFilter(corsConfig.corsFilter()); // @CrossOrigin(인증X), 시큐리티 필터에 등록인증(O)
// http.formLogin().disable();
http.formLogin((form)->
form.disable());
// http.httpBasic().disable();
http.httpBasic((basic)->
basic.disable());
http.addFilter(new JwtAuthenticationFilter(authenticationManager)); // AuthenticationManger
http.authorizeHttpRequests(authorize -> authorize.requestMatchers("/user/**").authenticated()
.requestMatchers("/manager/**").hasAnyRole("ADMIN", "MANAGER")
.requestMatchers("/admin/**")
.hasAnyRole("ADMIN").anyRequest().permitAll());
return http.build();
}
}
JwtAuthenticationFilter
// 스프링 시큐리티에서 UsernamePasswordAuthenticationFilter 가 있음
// /login 요청해서 username, password 전송하면 (post)
// UserPasswordAuthenticationFilter가 동작을 함
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
// /login 요청을 하면 로그인 시도를 위해서 실행되는 함수
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
System.out.println("로그인 시도: JwtAuthenticationFilter");
return super.attemptAuthentication(request, response);
}
}
답변을 작성해보세요.
-5
인프런 AI 인턴
2024.01.19
안녕하세요, 인프런 AI 인턴입니다.
정정모님, authenticationManager()
관련하여 문제가 발생했을 때 해결할 수 있는 방법을 알려드리겠습니다.
이 경우 SecurityConfig
클래스 내에서 authenticationManagerBean()
메소드를 직접 오버라이드 하여 AuthenticationManager
를 빈으로 등록하면 문제를 해결하실 수 있습니다. 예를 들어:
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
위 코드를 SecurityConfig
클래스에 추가해 주시면 됩니다. 이렇게 함으로써 Spring Security의 AuthenticationManager
를 외부에서 주입받을 수 있게 되어, JwtAuthenticationFilter
에서 사용할 수 있게 됩니다.
위의 해결 방법이 도움이 되셨기를 바랍니다. 문제가 계속된다면 프로젝트의 스프링 시큐리티 설정 부분을 좀 더 면밀히 검토하셔야 할 수도 있습니다.
답변 1