복붙노트

[SPRING] @PreAuthorize 주석이 스프링 보안을 작동하지 않음

SPRING

@PreAuthorize 주석이 스프링 보안을 작동하지 않음

비슷한 질문을 많이 발견했지만 아무도 내 문제를 해결하지 못했습니다. 내 문제는 ROLE_USER가 ROLE_ADMIN의 기능에 액세스 할 수 있다는 것입니다.

내 spring-security.xml 코드는 다음과 같다.

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:s="http://www.springframework.org/schema/security"
   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/security
                    http://www.springframework.org/schema/security/spring-security-3.0.xsd">   

<s:http auto-config="true" use-expressions="true">
    <s:intercept-url pattern="/index.jsp" access="permitAll" />
    <s:intercept-url pattern="/welcome*" access="hasRole('ROLE_USER')" />
    <s:intercept-url pattern="/helloadmin*" access="hasRole('ROLE_ADMIN')" />

    <s:form-login login-page="/login" default-target-url="/welcome"
        authentication-failure-url="/loginfailed" />
    <s:logout logout-success-url="/logout" />
</s:http>

<s:authentication-manager>
  <s:authentication-provider>
    <s:user-service>
        <s:user name="asif" password="123456" authorities="ROLE_USER,ROLE_ADMIN" />
        <s:user name="raheel" password="123456" authorities="ROLE_USER" />          
    </s:user-service>
  </s:authentication-provider>
</s:authentication-manager>

를 추가하면 내 코드가 리소스를 찾을 수 없음 오류를 표시하고 코드를 성공적으로 제거했지만 ROLE_USER가 ROLE_ADMIN 함수에 액세스 할 수 있음

내 컨트롤러 기능입니다.

@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value="/delete", method = RequestMethod.GET)
public String DeleteAll(ModelMap model, Principal principal ) {

    org.springframework.security.core.userdetails.User activeUser = (org.springframework.security.core.userdetails.User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    System.out.println("Active user is "+activeUser.getUsername()+"Authorities are "+activeUser.getAuthorities());
    return "deleteUsers";

}

해결법

  1. ==============================

    1.너는 ~해야한다.

    너는 ~해야한다.

    <s:global-method-security pre-post-annotations="enabled"/>
    

    @PreAuthorize 주석을 사용하려면.

    의견에 대답하려면 :

    당신이 봄철에 의존하지 않는 것처럼 보입니다.

    Maven을 사용하는 경우 다음이 필요합니다.

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>
    

    그렇지 않다면 여기에서 항아리를 얻을 수 있습니다.

  2. ==============================

    2.XML 구성을 사용하는 경우 다음 특성을 추가하는 것을 잊지 마십시오.

    XML 구성을 사용하는 경우 다음 특성을 추가하는 것을 잊지 마십시오.

    Java 구성을 사용하는 경우 다음 주석을 추가하는 것을 잊지 마십시오.

    @EnableGlobalMethodSecurity (prePostEnabled = true)

  3. ==============================

    3.나는 같은 문제에 직면했다. 내 문제는 applicationContext.xml에서 아래의 요소를 * -servlet.xml (내 디스패처 구성 xml)로 옮겼을 때 해결되었습니다.

    나는 같은 문제에 직면했다. 내 문제는 applicationContext.xml에서 아래의 요소를 * -servlet.xml (내 디스패처 구성 xml)로 옮겼을 때 해결되었습니다.

    <security:global-method-security secured-annotations="enabled"/>
    

    응용 프로그램의 XML이 아닌 발송자의 XML에이 요소를 포함해야합니다. 봄 자주 묻는 질문

  4. ==============================

    4.@Secured 주석으로 시도해보십시오.

    @Secured 주석으로 시도해보십시오.

    그럼 네가 가질거야.

    @Secured("ROLE_ADMIN")
    @RequestMapping(value="/delete", method = RequestMethod.GET)
    public String DeleteAll(ModelMap model, Principal principal ) {
    
      ...
    
    }
    

    여기에 대한 자세한 블로그 게시물이 있습니다.

  5. ==============================

    5.위의 답변 중 어느 것도 저에게 효과가 없습니다. 나는 보안 장식을 추가하는 길을 가야했다.

    위의 답변 중 어느 것도 저에게 효과가 없습니다. 나는 보안 장식을 추가하는 길을 가야했다.

    데코레이터는 파일 servlet-context.xml 내의 빈에 배치됩니다.

    먼저 보안 스키마를 XML 네임 스페이스에 추가합니다.

    <beans:beans xmlns="http://www.springframework.org/schema/mvc"
    ...
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    

    그런 다음 서비스 bean의 구현에 데코레이터를 적용한다.

    <beans:bean id="myService" class="my.service.impl.MyServiceImpl" scope="request">
        <security:intercept-methods>
            <security:protect access="ROLE_USER" method="get*"/>
            <security:protect access="ROLE_ADMIN" method="set*"/>
        </security:intercept-methods>
    </beans:bean>
    
  6. ==============================

    6.내가 주석과 함께 작업하는 동일한 문제가 있었는데 문제는 컨트롤러에 @Controller 주석이 없다는 것이 었습니다.

    내가 주석과 함께 작업하는 동일한 문제가 있었는데 문제는 컨트롤러에 @Controller 주석이 없다는 것이 었습니다.

    그래서 당신이 필요해 보인다 :

    또한 문제가 계속되는 경우 log4j2 구성에 추가하는 것이 좋습니다.

        <Logger name="org.springframework.security" level="trace" additivity="false">
            <AppenderRef ref="Console" />
            <AppenderRef ref="RollingRandomAccessFile" />
        </Logger>
    

    스프링에 의해 주석이 고려되는 경우 로그에 표시됩니다.

    TRACE org.springframework.security.access.prepost.PrePostAnnotationSecurityMetadataSource {} [main] Looking for Pre/Post annotations for method 'wsAdmin' on target class '***.ServiceRS' 
    DEBUG org.springframework.security.access.prepost.PrePostAnnotationSecurityMetadataSource {} [main] @org.springframework.security.access.prepost.PreAuthorize(value=hasAuthority('ROLE_ADMIN')) found on specific method: public void ***.ServiceRS.wsAdmin() 
    DEBUG org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource {} [main] Caching method [CacheKey[***.ServiceRS; public void ***.ServiceRS.wsAdmin()]] with attributes [[authorize: 'hasAuthority('ROLE_ADMIN')', filter: 'null', filterTarget: 'null']] 
    

    그리고 분명히 org.springframework.security.access.expression.SecurityExpressionRoot의 해당 메소드에 중단 점을 추가하여 주석이있는 조건으로 호출이 완료되었는지 확인할 수 있습니다.

    문안 인사.

  7. ==============================

    7.도움이 될 수 있습니다.

    도움이 될 수 있습니다.

    <security:global-method-security secured-annotations="enabled" proxy-target-class="true"/>
    

    문안 인사.

  8. ==============================

    8.이 문제는 웹 비동기 지원과 함께 Servlet 3을 사용할 때 발생합니다. Spring Security 3.1.4와 그 이하 버전은 Callable 메소드의 익명 메소드를 일단 입력하면 보안 컨텍스트를 잃어 버립니다.

    이 문제는 웹 비동기 지원과 함께 Servlet 3을 사용할 때 발생합니다. Spring Security 3.1.4와 그 이하 버전은 Callable 메소드의 익명 메소드를 일단 입력하면 보안 컨텍스트를 잃어 버립니다.

    Spring Security를 ​​3.2.0 RC1로 업그레이드하면 문제가 해결됩니다.

    Maven 종속성 :

    <dependencies>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>3.2.0.RC1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>3.2.0.RC1</version>
        </dependency>
    </dependencies>
    
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    
  9. ==============================

    9.Spring 보안 설정 파일이 아닌 다른 Spring 설정 파일에 태그 아래에 놓는다.

    Spring 보안 설정 파일이 아닌 다른 Spring 설정 파일에 태그 아래에 놓는다.

    나는 또한 같은 오류를 받고 있었다.

    <security:global-method-security secured-annotations="enabled" proxy-target-class="true"/>
    
  10. from https://stackoverflow.com/questions/11841156/preauthorize-annotation-not-working-spring-security by cc-by-sa and MIT license