我的设置:
在Spring MVC 3.1应用程序中,我有一个Spring Security保护服务:
@PreAuthorize("isAnonymous()") // ("hasRole('USER')") doesn't work either
public interface UserService extends UserDetailsService, PasswordEncoder
我正在尝试在我的上下文中声明的bean的init()方法中使用此服务:
<bean class="com.xxx.scripts.FillDbWithInitialValues" init-method="contextInit" />
班级:
public class FillDbWithInitialValues
{
@Autowired
UserService userService;
public void contextInit()
{
User test = userService.getUser(1);
}
}
我的security.xml文件的摘录:
<sec:global-method-security pre-post-annotations="enabled" />
<sec:http auto-config="true" use-expressions="true">
(...)
</sec:http>
<sec:authentication-manager alias="authManager">
<sec:authentication-provider user-service-ref="userService">
<sec:password-encoder ref="userService" />
</sec:authentication-provider>
</sec:authentication-manager>
问题:
当我启动应用程序时,我得到一个例外:
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
为什么会这样? 我的bean如何“经过身份验证”以便它可以使用该服务?
答案 0 :(得分:0)
如果没有用户通过身份验证,则无法检查其角色。如果你想在调用方法之前对bean进行身份验证,我认为你可以用这种方式尝试:
SecurityContextHolder.getContext().setAuthentication(new user here);
User test = userService.getUser(1);