로그인 요청시 401 상태 반환
미해결
Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)
로그인 시도 시 401 오류를 반환하고 있습니다. user-service의 AuthenticationFilter 에서 인증이 실패가 된지 알아 디버깅을 해보니 인증이 성공해서 도대체 어디가 문제인지 알 수가 없습니다. 그래서 유저 서비스에 직접 접근을 할 시 똑같은 401 오류를 반환하고 있습니다. 그리고 유저 서비스에 직접 접근을 하거나 게이트웨이로 접근해도 성공에 관한 메소드는 작동하지 않습니다. < 스프링 부트, 시큐리티는 현재 최신 버전입니다. > AuthenticationFilter 클래스 @RequiredArgsConstructor @Slf4j public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final UserService userService; @Value("${token.expiration_time}") private Long EXPIRATION_TIME; @Value("${token.secret}") private String secretKey; @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { log.info("attemptAuthentication"); try{ RequestLoginVo cred=new ObjectMapper().readValue(request.getInputStream(), RequestLoginVo.class); log.info(cred.getEmail()+" "+cred.getPassword()); return this.getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken( cred.getEmail(), cred.getPassword(), new ArrayList<>() )); } catch(IOException e){ throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { String userName = ((User)authResult.getPrincipal()).getUsername(); UserDto userDto = userService.getUserDetailByEmail(userName); String token = Jwts.builder() .setSubject(userDto.getUserId()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) .signWith(SignatureAlgorithm.HS512, secretKey) .compact(); response.addHeader("token",token); response.addHeader("userId",userDto.getUserId()); } } loadUserByUsername 메소드 @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { log.info("loadUserByUsername "+username); Optional<UserEntity> userEntity = userRepository.findByEmail(username); log.info(userEntity.get().getEmail()+" "+userEntity.get().getName()+" "+userEntity.get().getEncryptedPwd()); if(userEntity.isEmpty()){ throw new UsernameNotFoundException("해당 유저는 존재하지 않습니다."); } return new User(userEntity.get().getEmail(), userEntity.get().getEncryptedPwd(), true, true, true, true, new ArrayList<>()); } WebSecurity 클래스 @Configuration @EnableWebSecurity @RequiredArgsConstructor public class WebSecurity{ private final BCryptPasswordEncoder bCryptPasswordEncoder; private final UserService userService; @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .headers(headers -> headers .frameOptions((frameOptions) -> frameOptions.disable())) .authorizeRequests(authorize -> authorize .requestMatchers(PathRequest.toH2Console()).permitAll() .requestMatchers("/**").hasIpAddress("127.0.0.1") ) .addFilter(getAuthenticationFilter()); return http.build(); } @Bean public AuthenticationManager authenticationManager() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setUserDetailsService(userService); provider.setPasswordEncoder(bCryptPasswordEncoder); return new ProviderManager(provider); } private AuthenticationFilter getAuthenticationFilter() { AuthenticationFilter authenticationFilter = new AuthenticationFilter(userService); authenticationFilter.setAuthenticationManager(authenticationManager()); return authenticationFilter; } } ApiGateWay - Application.yml 유저 서비스 부분 routes: - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/login - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/users - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/** - Method=GET filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*) , /$\{segment} - AuthorizationHeaderFilter
- spring-boot
- jpa
- 아키텍처
- spring-cloud
- kafka
- msa





