authenticationManager 관련 질문입니다.
1883
작성한 질문수 5
안녕하세요 늘 좋은 강의 올려주셔서 감사합니다.
authenticationManager 파라미터 전달 부분에서 문제가 있어 이렇게 게시글 남깁니다!
새로 올려주신 소스코드를 보며 새로 업데이트된 시큐리티에서 사용하기위해 authenticationManager 를 파라미터로 전달하는 부분을 적용하였습니다 그런데
Authentication authentication =
authenticationManager.authenticate(authenticationToken);부분에서 loadbyUsername() 함수를 호출하지 못하고 있습니다...
JwtAuthenticationFilter
// 유저네임 패스워드 토큰 생성
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(
loginUser.getUsername(),
loginUser.getPassword()
);
System.out.println("JwtAuthenticationToken : 토큰생성완료");
// authenticate() 함수가 호출 되면 인증 프로바이더가 유저 디테일 서비스의
// loadUserByUsername(토큰의 첫번째 파라메터) 를 호출하고
// UserDetails를 리턴받아서 토큰의 두번째 파라메터(credential)과
// UserDetails(DB값)의 getPassword()함수로 비교해서 동일하면
// Authentication 객체를 만들어서 필터체인으로 리턴해준다.
// Tip: 인증 프로바이더의 디폴트 서비스는 UserDetailsService 타입
// Tip: 인증 프로바이더의 디폴트 암호화 방식은 BCryptPasswordEncoder
// 결론은 인증 프로바이더에게 알려줄 필요가 없음.
Authentication authentication =
authenticationManager.authenticate(authenticationToken);
System.out.println("authentication : authentication 생성 완료");
PrincipalDetails principalDetails = (PrincipalDetails) authentication.getPrincipal();
System.out.println("Authentication : " + principalDetails.getUser().getUsername());
return authentication;SecurityConfig
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final CosConfig cosConfig;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
http.csrf(csrf -> csrf.disable());
http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
http.addFilter(cosConfig.corsFilter()); // cors 허용 설정
http.addFilterBefore(new MyFilter3(), SecurityContextPersistenceFilter.class);
http.formLogin(login -> login.disable());
http.httpBasic(basic -> basic.disable());
http.addFilter(new JwtAuthenticationFilter(authenticationManager));
http.authorizeHttpRequests(request ->
request.requestMatchers("/api/v1/user/**")
.hasAnyRole("USER", "MANAGER", "ADMIN")
.requestMatchers("/api/v1/manager/**")
.hasAnyRole("MANAGER", "ADMIN")
.requestMatchers("/api/v1/admin/**")
.hasRole("ADMIN")
.anyRequest().permitAll()
);
return http.getOrBuild();
}
와 같이 SecurityConfig를 업데이트된 Spring Security 독스를 보고 선생님께서 강의해주신 내용대로 만들어보았습니다.
터미널에서는
JwtAuthentication Filter : 로그인 시도중
JwtAuthenticationFilter : UserEntity(id=0, email=null, password=qwer1234, username=ssar, role=null, createDate=null)
JwtAuthenticationToken : 토큰생성완료와 같이 JwtAuthenticationToken : 토큰생성완료 까지는 정상적으로 되는걸 확인하였습니다.
이후 loadByUsername() 부분에 따로 출력을 찍어 확인한결과 호출이 안되는걸 확인했습니다.
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserEntity userEntity = this.userDao.findByUsername(username);
System.out.println("================ loadUserByUsername ================");
System.out.println(userEntity);
System.out.println("---------------- loadUserByUsername -----------------");
return new PrincipalDetails(userEntity);
}
어떤 부분이 잘못되어서 그런건지 찾지 못하여 게시글 남깁니다! 늘 좋은강의 감사합니다!
개인적으로 문제점이 된다고 생각한 부분
AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
에서 authenticationManager를 받는 부분이 제대로 안되는것 같습니다...
추가로 SecurityConfig 에서 authenticationManager 부분을 로그로 찍어본 결과 null 출력되는걸 확인했습니다... authenticationManager부분이 생성이 안되는걸까요?
답변 1
2
구글링을 통해 해결했습니다!
혹시 다른분들도 Spring Security 6.x 로 하고싶은분이 있으실태니까 글 남겨놓겠습니다!
AuthenticationManagerBuilder sharedObject = http.getSharedObject(AuthenticationManagerBuilder.class);
sharedObject.userDetailsService(this.userDetailsService);
AuthenticationManager authenticationManager = sharedObject.build();
http.authenticationManager(authenticationManager);authenticationManager 생성부분을 위와같이 교채해 주시면 됩니다!
JWT를 구현한 다음 이 API를 호출해서 사용하는 것은 프론트엔드 쪽에서 하는 역할인가요?
0
95
1
Jwt쓰면 스프링시큐리티는 필수적으로 사용해야하나요?
0
401
1
13:23 system.out 출력문이 다르게 나옵니다.
0
130
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
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
339
1
jwt와 실제데이터의 관계
1
243
1
jwt 와 세션ID의 관계
1
312
1
SecurityConfig에서 세션 설정, 인가 설정
0
419
1





