这里有我的 Controller 方法:
@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 Access is denied
编辑
为了填充主体,我使用自定义过滤器:
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("principal.username == '" + EspaiDocConstants.BO_COMPONENT_APP + "'")
关于java - Spring启动测试: User protected security controller on testing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54421692/