初始安全性初始化懒惰bean中的身份验证对象

时间:2013-06-18 17:09:53

标签: java spring spring-security

我将Roles的Spring安全性实现到Authentication对象中,用于通过@Secure("ROLE")注释来限制我的服务中的访问。 一切看起来都很好,而且对于不太好的身份验证,Roles Spring Security会抛出Access Denied Exception

我的问题来自我的Integration测试,因为我在测试开始之前使用了一些init lazy bean来加载一些信息,并且在我尝试访问这些有限服务的那一刻,我收到{ {1}} 在我的单元测试中,我实现了解决相同的问题,并使用安全注释创建Access denied exception.对象的一些服务,并添加到Authentication

SpringContextHolder

但是当我启动我的Jetty Server进行集成测试,并且我的init懒惰的bean正在运行并运行此代码时,情况就像在单元测试中一样,而Spring则抛出 List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ADMIN_ROLE"); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("test@test.com", "test", authorities); SecurityContextHolder.getContext().setAuthentication(authentication); 因为不能在Access denied exception中找到任何Authentication个对象。

有人可以帮助我!

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我发现使用@PreAuthorize(“hasRole('USER_ROLE')”)在init lazy bans运行期间正在运行。所以我可以避免在我的会话中添加SecurityContext。 abd感谢主,因为init lazy bean不是Servlet所以不可能做出你的建议

相关问题