Spring Security 在Controller上使用@RolesAllowed并获取“object不是声明类的示例”

lqfhib0f  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(88)

我试图使用方法安全性,所以我把dispatcher-servlet.xml(security.xml在另一个上下文中):

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

并将@RolesAllowed放在Controller上:

@SessionAttributes({"sessionCompanyDetails"})
@Controller
@RequestMapping("/company")
@RolesAllowed("ROLE_ADMIN")
public class CompanyController extends BaseController {
  ...

我意识到,当我使用这些注解时,Spring会为Controller创建一个Proxy,因此我会得到错误:

java.lang.IllegalArgumentException:object is not an instance of declaring class
nhaq1z21

nhaq1z211#

问题的发生是因为Controller没有接口,所以Spring创建了一个代理,但不能转换为Controller类。
可能的解决方案是:
1.拦截器:使用MethodSecurityInterceptor和Exclusive DecisionManager
1.使用<global-method-security proxy-target-class="true"/>激活CGLib代理(代理类是子类),所以Spring可以强制转换它。
1.创建到Controller的接口。
1.使用ANOW J.
我测试了所有的解决方案,但APDJ。我在一个项目中使用CGLib解决方案,在另一个项目中使用Interceptor,两种解决方案都工作得很好。

相关问题