【问题标题】:Spring security Authentication object in init lazy beans初始化惰性bean中的Spring安全身份验证对象
【发布时间】:2013-06-20 19:14:12
【问题描述】:

我在 Authentication 对象中使用 Roles 实现 Spring 安全性,用于通过 @Secure("ROLE") 注释限制我的服务中的访问。 一切似乎都很好,并且对于身份验证不好的角色 Spring Security 抛出 Access Denied Exception

我的问题出现在我的集成测试中,因为我正在使用一些 init 惰性 bean 以便在测试开始之前加载一些信息,并且在那一刻,当我试图访问这个有限的服务时,我收到了 @ 987654325@ 在我的单元测试中,我解决了同样的问题,并使用了一些带有安全注释的服务,创建了Authentication 对象,并添加到SpringContextHolder

  List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ADMIN_ROLE");
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("test@test.com", "test", authorities);
    SecurityContextHolder.getContext().setAuthentication(authentication);

但是当我启动我的 Jetty 服务器进行集成测试时,我的 init 惰性 bean 正在运行并运行此代码,情况不像在单元测试中那样工作,并且 Spring 向我抛出 Access denied exception 因为找不到任何SecurityContext 中的Authentication 对象。

有人可以帮帮我!

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    您需要将 SecurityContext 附加到会话。由于它是线程绑定的,否则它将丢失以备将来使用。有关详细信息,请参阅以下答案。 https://stackoverflow.com/a/16778652/2319179

    【讨论】:

      【解决方案2】:

      我发现在初始化惰性禁令运行期间使用 @PreAuthorize("hasRole('USER_ROLE')") 正在工作。所以我可以避免在我的会话中添加 SecurityContext。 Abd 感谢主,因为 init 惰性 bean 不是 Servlet,所以不可能按照您的建议进行

      【讨论】:

        猜你喜欢
        • 2021-12-27
        • 1970-01-01
        • 2017-06-18
        • 2011-05-04
        • 2016-08-15
        • 1970-01-01
        • 1970-01-01
        • 2019-02-07
        • 2011-10-24
        相关资源
        最近更新 更多