开启Spring安全性的Spring webflow单元测试



我正在测试一个带有spring安全性的webflow控制器:

<action-state id="search">
    <secured attributes="ROLE_ADMIN"/>
...
</action-state>

我使用AbstractXmlFlowExecutionTests子类。

现在,没有"secured"标记的测试可以正常运行(我没有对安全性进行任何模拟),但是一旦添加了安全标记,测试就会成功结束,尽管我预计会抛出一个安全异常。知道为什么它不能工作,我应该如何配置它吗?提前感谢!Igor

好了,我找到了解决方案:我需要手动添加securityListener。startFlow前:

setFlowExecutionListener(getSecurityListener(new String[] {"ROLE_ADMIN_FAKE"}));

,

private FlowExecutionListener getSecurityListener(String[] roles) {
    List<GrantedAuthority> result = new ArrayList<>();
    for (String role: roles) {
        SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role);
        result.add(authority);
    }
    Authentication auth = new PreAuthenticatedAuthenticationToken("Igor", "", result);
    SecurityContextHolder.getContext().setAuthentication(auth);
    return new SecurityFlowExecutionListener();
}

最新更新