인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

인프런 커뮤니티 질문&답변

망치님의 프로필 이미지

작성한 질문수

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

로그인 에러

작성

·

64

0

안녕하세요 강사님! 질문이 있어서 작성합니다.

현재 섹션 7까지 수강한 상태입니다.

회원가입을 하고 로그인을 시도했는데 회원가입은 정상, 로그인은 에러가 반환됩니다.

 

1) 섹션 19(165강)에서 WebSecurity 코드로 실행

image.pngimage.pngimage.png스크린샷 2025-03-17 015804.png
package com.example.user_service.sercurity;

import com.example.user_service.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.expression.WebExpressionAuthorizationManager;
import org.springframework.core.env.Environment;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.IpAddressMatcher;

import java.util.function.Supplier;

@Configuration
@EnableMethodSecurity
public class WebSecurity {
    private final UserService userService;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;
    private final Environment env;

    public static final String ALLOWED_IP_ADDRESS = "127.0.0.1";
    public static final String SUBNET = "/32";
    public static final IpAddressMatcher ALLOWED_IP_ADDRESS_MATCHER = new IpAddressMatcher(ALLOWED_IP_ADDRESS + SUBNET);

    public WebSecurity(Environment env, UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder){
        this.env = env;
        this.userService = userService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder authenticationManagerBuilder =
                http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
        return authenticationManagerBuilder.build();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf((csrf) -> csrf.disable())
                .authorizeHttpRequests((authz) -> authz
                        .requestMatchers(new AntPathRequestMatcher("/actuator/**")).permitAll()
                        .requestMatchers(new AntPathRequestMatcher("/h2-console/**")).permitAll()
                        .requestMatchers(new AntPathRequestMatcher("/users", "POST")).permitAll()
                        .requestMatchers(new AntPathRequestMatcher("/welcome")).permitAll()
                        .requestMatchers(new AntPathRequestMatcher("/health_check")).permitAll()
                        .anyRequest().access(
                                new WebExpressionAuthorizationManager(
                                        "hasIpAddress('127.0.0.1') or hasIpAddress('192.168.219.119')"))
                )
                .sessionManagement((session) -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .headers((headers) -> headers.frameOptions((frameOptions) -> frameOptions.disable()));

        return http.build();
    }

    private AuthorizationDecision hasIpAddress(Supplier<Authentication> authentication, RequestAuthorizationContext object){
        return new AuthorizationDecision(ALLOWED_IP_ADDRESS_MATCHER.matches(object.getRequest()));
    }
}

2) https://github.com/joneconsulting/toy-msa/tree/springboot3.2 에서 'springboot3.2' 브런치의 'WebSecurityNew', 'IpAddressLoggingFilter' 코드로 실행

image.png

 

image.png

 

imageimage.png

그리고 IpAddressLoggingFilter 코드에 대한 강의도 있나요?

 

답변 1

0

인프런 AI 인턴님의 프로필 이미지

안녕하세요, 인프런 AI 인턴입니다.
로그인 시 404 오류가 발생하는 문제와 관련하여 몇 가지 점검 사항을 확인해보겠습니다.

  1. EndPoint URL 확인:

    • 요청 URL이 /user-service/login으로 되어 있는 것 같습니다. 이 경로가 Spring Security 설정에 맞게 설정되어 있는지 확인해야 합니다. WebSecurity 구성에서 POST 요청에 대한 /login 경로가 허용되고 있는지 확인하세요.
  2. Security 설정 확인:

    • Spring Security에서 로그인 요청을 처리하는 경로가 올바르게 설정되어 있는지 확인해야 합니다. 특정 경로에 대한 권한이나 인증 설정이 잘못되었을 수 있습니다. 예를 들어, /login 경로에 대한 인증이 제대로 설정되어 있는지 확인하세요.
  3. Jwt 설정:

    • io.jsonwebtoken.lang.UnknownClassException 오류는 JWT 관련 라이브러리 문제일 가능성이 큽니다. 사용하는 JWT 라이브러리가 프로젝트의 classpath에 제대로 추가되어 있는지 확인해보세요. 예를 들어, jjwt-impl.jar이 누락되었는지 검토해야 할 것입니다.
  4. IpAddressLoggingFilter 강의:

    • 현재 제공된 정보에서 IpAddressLoggingFilter 코드에 관한 강의 정보를 찾을 수 없습니다. 강의 자료나 프로젝트 문서에서 해당 내용을 다시 한번 검토해보세요.

위의 사항을 점검하고 수정하신 후에 다시 시도해 보시기 바랍니다. 문제가 지속된다면 구체적인 설정이나 코드 부분을 추가로 점검해야 할 수도 있습니다. Spring Boot와 Spring Security 설정 관련 부분을 다시 확인해보시길 권장드립니다.

추가적으로, Spring Security 설정에 대한 더 자세한 정보는 Spring Security Reference Guide에서 확인하실 수 있습니다.

망치님의 프로필 이미지

작성한 질문수

질문하기