Spring @Secured 和 @PreAuthorize 在普通(非网络)应用程序中不起作用 [英] Spring @Secured and @PreAuthorize have no effect in plain (non-web) application

查看:61
本文介绍了Spring @Secured 和 @PreAuthorize 在普通(非网络)应用程序中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用两个安全方法创建了一个 Application Spring 组件:

I created a Application Spring component with two secured methods:

@Component
public class Application {

    public void run() {
        onlyAdminMethod();
        onlyAdminMethod2();
    }

    @Secured( "ROLE_ADMIN" )
    public void onlyAdminMethod() {
        System.out.println( "Admin-only method called" );
    }

    @PreAuthorize( "hasRole('ROLE_ADMIN')" )
    public void onlyAdminMethod2() {
        System.out.println( "Admin-only method 2 called" );
    }
}

我对该 bean 调用了 run() 方法,该方法是从 Spring XML 上下文中获取的:

I call run() method on that bean, which I take from Spring XML context:

ClassPathXmlApplicationContext context = 
     new ClassPathXmlApplicationContext("applicationContext.xml");  
context.getBean( Application.class).run();

什么都没有发生 - 方法被正常调用,即使没有身份验证并且 SecurityContextHolder.getContext().getAuthentication() 返回 null

Nothings happen - methods are called normally even if there is no authentication and SecurityContextHolder.getContext().getAuthentication() returns null

我的 Spring XML:

<context:annotation-config />
<context:component-scan base-package="practice" />

<security:authentication-manager>
   <security:authentication-provider>
      <security:user-service>
         <security:user name="admin" password="stackoverflow" authorities="ROLE_USER,ROLE_ADMIN" />
      </security:user-service>
   </security:authentication-provider>
</security:authentication-manager>

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

我为 Spring 3.2.4

推荐答案

2 Things

Spring 使用基于代理的 AOP 解决方案.这意味着只拦截外部方法调用,您进行内部方法调用,而那些绕过代理.

Spring uses a proxy based solution for AOP. Which means only external method calls are intercepted, you are making internal method calls and those bypass the proxy.

第二,确保您使用的是基于类的代理(您没有使用接口,因此 JDK 动态代理将不起作用).将 proxy-target-class="true" 添加到您的 <global-method-security ../> 元素.确保类路径上有 cglib,因为这是基于类的代理所必需的.

Second make sure you are using class based proxies (you aren't using interfaces so JDK Dynamic Proxies won't work). Add proxy-target-class="true" to your <global-method-security .. /> element. Make sure you have cglib on your classpath as that is required for classbased proxies.

这篇关于Spring @Secured 和 @PreAuthorize 在普通(非网络)应用程序中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆