【问题标题】:Cast object when authenticating on tests对测试进行身份验证时投射对象
【发布时间】:2013-08-23 15:47:33
【问题描述】:

我的 Spring 应用程序中有以下方法

public static String getCurrentUserStudentId() {
    return ((LdapPerson) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getID();
}

这适用于应用程序运行,但是当我运行一个调用此方法的测试时,它给出了

org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken cannot be cast to fi.utu.security.ldap.userdetails.LdapPerson

我对 Spring Security 不太熟悉,无法提供所有可能相关的文件,但请询问我。我希望有人能告诉我该怎么做。

【问题讨论】:

    标签: spring testing spring-security spring-security-ldap


    【解决方案1】:

    SecurityContextHolder 在静态变量中保留对“策略”的引用,这意味着此详细信息会从测试泄漏到测试。

    您有多种选择:

    1. 在您的测试中,使用SecurityContextHolder 的设置器之一设置正确的策略

    2. getCurrentUserStudentId 创建一个模拟实现,它返回一个固定的测试结果。

    3. 将获取当前用户 ID 的代码放入一个 bean 中并注入它,而不是调用 SecurityContextHolder。实现这个 bean 的两个版本:一个调用 SecurityContextHolder,另一个返回一个字符串。

    【讨论】:

    • 我认为只在测试类中保留修改会很好。你能给我一个设置测试策略的代码示例吗?我不确定你的意思。
    • 查看调用setContext()setStrategyName()的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 2017-09-18
    • 2017-03-11
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多