eajniii / chijin_final

1 stars 1 forks source link

[Trouble-Shooting] 스프링 시큐리티 설정을 위한 context-security.xml 파일 작성 중 오류 발생 #32

Closed jisoo449 closed 6 months ago

jisoo449 commented 6 months ago

문제 설명

https://sjh836.tistory.com/165, https://melonpeach.tistory.com/137 사이트를 참고하여 context-security.xml 파일 설정 후 프로젝트 실행 시 다음과 같은 오류 발생

해결방법

  1. pom.xml에 스프링 dependency 추가
    <properties>
                ...
        <spring.security.version>4.0.4.RELEASE</spring.security.version>
    </properties>
        . . .
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
       </dependency>
       <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
       </dependency>    
  2. context-security.xml 파일 생성

    
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/jdbc  http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">
    
    <bean id="dataSourceSpied" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@10.0.16.187:1521:xe" />
        <property name="username" value="c##admin" />
        <property name="password" value="DNFLRKskadlrk#2" />
    </bean>
    
    <bean id="dataSource" class="net.sf.log4jdbc.Log4jdbcProxyDataSource">
        <constructor-arg ref="dataSourceSpied" />
        <property name="logFormatter">
            <bean class="net.sf.log4jdbc.tools.Log4JdbcCustomFormatter">
                <property name="loggingType" value="MULTI_LINE" />
                <property name="sqlPrefix" value="SQL         :  "/>
            </bean>
        </property>
    </bean>
    </beans>

참고: https://sjh836.tistory.com/165, https://melonpeach.tistory.com/137, https://taetae0079.tistory.com/2,

jisoo449 commented 6 months ago

오류 내용

심각: Context initialized 이벤트를 [org.springframework.web.context.ContextLoaderListener] 클래스의 인스턴스인 리스너에 전송하는 동안 예외 발생

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot create inner bean '(inner bean)#639ea347' of type [org.springframework.security.web.csrf.CsrfFilter] while setting constructor argument with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#639ea347': Cannot resolve reference to bean 'userDeniedHandler' while setting bean property 'accessDeniedHandler'; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [egovframework.example.security.UserDeniedHandler] for bean with name 'userDeniedHandler' defined in file [D:\SeSAC\최종프로젝트\chijin_final\target\classes\config\spring\context-security.xml]; nested exception is java.lang.ClassNotFoundException: egovframework.example.security.UserDeniedHandler

심각: 하나 이상의 리스너들이 시작하지 못했습니다. 상세 내역은 적절한 컨테이너 로그 파일에서 찾을 수 있습니다.

jisoo449 commented 6 months ago

Bean definition exception error를 수정했더니 이번엔 bean creation exception이 뜨네요ㅠㅜ

jisoo449 commented 6 months ago

web.xml에 필터 추가하니 ContextLoaderListener 오류로 바뀜 해결해야 하는 문제는 다음과 같다

심각: Context initialized 이벤트를 [org.springframework.web.context.ContextLoaderListener] 클래스의 인스턴스인
리스너에 전송하는 동안 예외 발생
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 2 in XML document from file
[D:\SeSAC\최종프로젝트\chijin_final\target\classes\config\spring\context-security.xml] is invalid;
nested exception is org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 58;
"security:http" 요소에 대한 "security" 접두어가 바인드되지 않았습니다.

심각: 클래스 [org.springframework.web.context.ContextLoaderListener]의 인스턴스인 리스너에게 contextDestroyed
이벤트를 전송하는 중 예외 발생
java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh'
before accessing beans via the ApplicationContext
jisoo449 commented 6 months ago

web.xml에 정의한 필터체인 못찾음

심각: Context initialized 이벤트를 [org.springframework.web.context.ContextLoaderListener] 클래스의 인스턴스인
리스너에 전송하는 동안 예외 발생
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 
'org.springframework.security.filterChains': Cannot resolve reference to bean 
'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0];
 nested exception is org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0':
 Cannot create inner bean '(inner bean)#639ea347' of type 
[org.springframework.security.web.csrf.CsrfFilter] while setting constructor argument with key [3];
 nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean
with name '(inner bean)#639ea347': Cannot resolve reference to bean 'userDeniedHandler'
 while setting bean property 'accessDeniedHandler'; nested exception is 
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class 
[egovframework.example.security.UserDeniedHandler] for bean with name 'userDeniedHandler'
 defined in file [D:\SeSAC\최종프로젝트\chijin_final\target\classes\config\spring\context-security.xml];
 nested exception is java.lang.ClassNotFoundException: egovframework.example.security.UserDeniedHandler
jisoo449 commented 6 months ago

이번엔 db 접근이 안돼

jisoo449 commented 6 months ago

메이븐 업데이트를 해 보았다~~

jisoo449 commented 6 months ago

이번엔 jdbc 연결이 안돼ㅠㅜㅠ

jisoo449 commented 6 months ago

채린: jdbc 버전을 바꿔보삼~~

jisoo449 commented 6 months ago

인재: 스프링 시큐리티 자체가 다 막는거라서, 이거를 열어주는 자바 config 파일을 만들어야 함
https://wikidocs.net/162150

jisoo449 commented 6 months ago

context-security.xml에 설정을 해 주는 것인 듯?

jisoo449 commented 6 months ago

내일 아래 내용 보고 수정할 예정

<security:form-login> 태그에서 login-processing-url="/loginAction.do"로 설정했을 때 loginAction.do에서 에러가 발생하는 경우, 몇 가지 가능한 원인과 해결 방법을 고려해 볼 수 있습니다.

1. 컨트롤러에서 /loginAction.do 처리 누락

스프링 시큐리티는 login-processing-url에 지정된 경로로 POST 요청이 들어오면 자동으로 로그인 처리를 합니다. 따라서, 별도의 컨트롤러 메소드에서 이 URL을 처리하려고 하면 충돌이 발생할 수 있습니다. 이 경우, /loginAction.do에 대한 컨트롤러 메소드를 제거하거나 수정해야 합니다.

2. CSRF(Cross-Site Request Forgery) 토큰 누락

스프링 시큐리티는 기본적으로 CSRF 보호 기능을 활성화합니다. 로그인 폼에 CSRF 토큰이 포함되어 있지 않으면, 스프링 시큐리티는 요청을 거부하고 에러를 발생시킵니다.

해결 방법:

로그인 폼에 CSRF 토큰을 포함시키세요.

<form action="/loginAction.do" method="post">
    <input type="text" name="MEMBER_ID" />
    <input type="password" name="MEMBER_PASSWD" />
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    <input type="submit" value="Login" />
</form>

3. 스프링 시큐리티 설정 오류

<security:form-login> 설정이 올바르게 적용되지 않았을 수 있습니다. 예를 들어, context-security.xml 파일이 스프링 애플리케이션 컨텍스트에 올바르게 로드되지 않았거나, 다른 보안 설정이 로그인 프로세스와 충돌하는 경우가 있습니다.

해결 방법:

4. 로그 및 디버깅

에러의 구체적인 원인을 파악하기 위해 스프링 시큐리티 및 관련 컴포넌트의 로그 레벨을 DEBUG로 설정하여 로그를 확인하세요. 로그에서는 요청 처리 과정에서 발생하는 문제에 대한 자세한 정보를 제공할 수 있습니다.

<logger name="org.springframework.security" level="DEBUG"/>

이러한 단계를 통해 문제를 진단하고 해결할 수 있습니다. 문제가 계속되면, 에러 메시지의 내용과 함께 구체적인 설정 파일의 내용을 추가로 검토해야 할 수 있습니다.

jisoo449 commented 6 months ago

다음과 같이 context-security.xml 파일 설정했음

    <security:form-login username-parameter="MEMBER_ID" 
                         password-parameter="MEMBER_PASSWD" 
                         login-page="/loginForm.do" 
                         login-processing-url="/loginAction.do" 
                         default-target-url="/main.do"/>

    </security:http>


다음과 같은 오류 발생

image

jisoo449 commented 6 months ago

commandMap이 문제임