spring不强制执行方法安全注释

时间:2009-02-05 19:30:21

标签: java annotations spring-security

我失去了为什么spring没有在我的服务接口上强制执行@Secured(“ROLE_USER”)。我的控制器是使用注释建立的。

我的服务接口的一个例子

public interface MyServiceManager {

    @Secured("ROLE_USER")
    public void delete(int cid);

    @RolesAllowed({"ROLE_USER"})
    public Contact getContact(int contactId);
}

我的安全上下文:

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

<http auto-config="true" >
    <intercept-url pattern="/secure/**" access="ROLE_SUPERVISOR" />
    <intercept-url pattern="/addcontact**" access="IS_AUTHENTICATED_REMEMBERED" />
    <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />

    <concurrent-session-control max-sessions="1"
        exception-if-maximum-exceeded="true"/>
    <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1"/>
    <logout logout-success-url="/welcome.do" logout-url="/logout"/>
</http>
    <authentication-provider>
    <password-encoder hash="md5"/>
    <user-service>
        <user name="rod" password="a564de63c2d0da68cf47586ee05984d7" authorities="ROLE_SUPERVISOR, ROLE_USER, ROLE_TELLER" />
    </user-service>
</authentication-provider>

7 个答案:

答案 0 :(得分:7)

你有声明吗

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

在与您定义MyServiceManager bean的配置文件相同的配置文件中?在我打开org.springframework的调试之前,我遇到了同样的问题,并注意到spring安全性仅应用于与定义了global-method-security的文件相同的文件。

答案 1 :(得分:4)

就我而言,这句话的确切位置:

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

证明非常重要。确保在声明要扫描哪些类并将其用作控制器后

<context:component-scan base-package="com.test.controller" />

这是确保@Secured注释也将进入游戏的方法

答案 2 :(得分:2)

在对这个问题做了更多研究后,我得出以下结论/解决方案。我不确定它是否100%正确..但是它有效。

我将所有配置都放在dispatcher-servlet.xml文件中。因此,不要使用disptacher-servlet.xml和application-context.xml。 dispatcher-servlet.xml由应用程序加载(contextConfigLocation)。在dispatcher-servlet.xml中,我导入了security-context.xml和datasource-context.xml。更何况,一切正常。

答案 3 :(得分:2)

我有同样的问题。使用Kent Lai在这里回复的信息,我能够解决它。

我将<global-method-security>元素放在我的app-servlet.xml中,但保留了security.xml中的安全定义,其中web.xml contextConfigLocation app-servlet.xml security.xml和{{1}}。

现在就像魅力一样!

答案 4 :(得分:1)

尝试将注释放在实现类而不是接口上,看看是否有效。我最近在最近的一个项目上做了这个,因为我也在我的服务层上使用了@Transactional属性,Spring文档建议把它们放在类而不是接口上。我不知道同样的问题是否适用于@Secured,但我想将注释保留在同一个地方。请参阅Spring Docs

关于Kent Lai的回答......这是一个好主意......确保你的安全配置文件实际上被Spring包含。

答案 5 :(得分:1)

您是否在web.xml中使用了类似的内容

<servlet>
    <servlet-name>name</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/webmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

我不知道为什么,但是如果我使用DispatcherServlet我无法强制执行安全注释

答案 6 :(得分:0)

我有同样的问题。 我添加后:

<context:annotation-config />

在我的spring-security.xml文件中它消失了。

希望这会有所帮助:)