首页 > 解决方案 > 实现接口时未创建带有 @Secured 注释的类

问题描述

我有问题,不明白如何解决,任何帮助都会被评估。我需要使用一些身份验证来保护 REST 方法,并且我的应用程序中的角色很少。我将@Secured注释放在我的类中的方法中,该方法实现了一些接口,并且 Spring 没有创建@Controller没有任何日志消息的 bean(在我的情况下)。但是如果类没有实现接口——bean 就创建得很好。

在代码中它看起来像那里:

控制器:

public class Controller implements API {
   @Secured("ROLE_ADMIN")
   @RequestMapping(value = "/one/", method = RequestMethod.GET)
   public String test() {
      return "ONE";
   }
}

界面:

public interface API {
   String test();
}

在我的情况下,控制器 bean 没有创建。但是,如果我删除implements API所有内容将正常工作,将创建 bean 并且安全性将起作用。

我使用基于 XML 的配置和放置

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

mvc-config.xml中启用注释。

我跟踪它,如果注释放置在未实现接口的类中的方法上,SpringMethodSecurityMetadataSourceAdvisor.MethodSecurityMetadataSourcePointcut在构建上下文时使用,但当类实现接口时 - Spring 使用TransactionAttributeSourcePointcut

@RolesAllowed给出相同的效果。

检查版本

<spring.version>4.3.7.RELEASE</spring.version>
<spring-security.version>4.2.2.RELEASE</spring-security.version>

<spring.version>4.3.23.RELEASE</spring.version>
<spring-security.version>4.2.13.RELEASE</spring-security.version>

最新的Spring Boot也有同样的效果。

有人解决了同样的问题吗?非常感谢。

标签: javaspringspring-security

解决方案


尝试在您的配置类中的类级别添加 this-@EnableGlobalMethodSecurity(securedEnabled = true),我们可以在任何 @Configuration 实例上使用 @EnableGlobalMethodSecurity 注释启用基于注释的安全性。例如,以下将启用 Spring Security 的 @Secured 注解。

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig {
   // ...
}

推荐阅读