繁体   English   中英

春季启动测试:测试中受用户保护的安全控制器

[英]Spring boot testing: User protected security controller on testing

这里有我的控制器方法:

@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"

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

@PreAuthorize(“主要用户名 =='” + EspaiDocConstants.BO_COMPONENT_APP +“'”)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM