【问题标题】:Spring boot testing: User protected security controller on testingSpring Boot 测试:测试中用户保护的安全控制器
【发布时间】:2019-06-22 14:50:37
【问题描述】:

这里有我的控制器方法:

@PreAuthorize("principal == '" + EspaiDocConstants.BO_COMPONENT_APP + "'")
public void ingestAudits() {
    // Do something
}

如您所见,它使用@PreAuthorize("principal == '" + EspaiDocConstants.BO_COMPONENT_APP + "'") 进行保护

这是我的测试代码:

@WithMockUser(username=EspaiDocConstants.BO_COMPONENT_APP)
@Test
public void test() throws IOException, NoSuchAlgorithmException {
    this.controller.ingestAudits();
}

不过,我收到了这条异常消息:

DigestAuditsTest.test:91 » AccessDenied 访问被拒绝

编辑

为了填充主体,我使用了自定义过滤器:

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    @Override
    protected void doFilterInternal(
        HttpServletRequest req,
        HttpServletResponse res,
        FilterChain chain
    ) throws IOException, ServletException {
        String user = Jwts.parser().setSigningKey(SECRET)
            .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
            .getBody().getSubject();

        SecurityContextHolder.getContext()
            .setAuthentication(
                new UsernamePasswordAuthenticationToken(user, null)
            );

        chain.doFilter(req, res);
    }
}

所以,principal 是一个包含用户的String

除此之外,我现在无法更改此代码,我想知道如何使用@WithMockUser 向委托人提供"String user"

【问题讨论】:

    标签: java spring-boot spring-security spring-test spring-security-test


    【解决方案1】:

    您应该只验证用户名,而不是使用“==”验证整个主体对象。

    @PreAuthorize("principal.用户名 == '" + EspaiDocConstants.BO_COMPONENT_APP + "'")

    【讨论】:

    • 调试时是否调用了JWTAuthorizationFilter?
    猜你喜欢
    • 2017-06-08
    • 2014-10-25
    • 2016-05-28
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2017-10-03
    相关资源
    最近更新 更多