【发布时间】:2020-06-09 12:47:05
【问题描述】:
我有一个基于 Spring Boot 的应用程序,我们使用来自外部提供商的 ISAM 身份验证。
我有一个 rest/json 端点 /actuator/health,它根据用户是否经过身份验证返回不同的数据。
如何在单元测试期间模拟身份验证以确保我的配置正确?
在setup() 中,我尝试手动设置令牌,并覆盖 AuthorizationService 以返回 true。
@Before
public void setUp() throws Exception
{
mockMvc = webAppContextSetup(wac).apply(springSecurity()).build();
List roles = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken("dave", "secret",
roles);
if (!auth.isAuthenticated()) { fail("NOT AUTHENTICATED!"); }
SecurityContextHolder.getContext().setAuthentication(auth);
//fake logged in
when(authorizationService.isCurrentUserAuthorized(anyString(),
anyString(),
ArgumentMatchers.any(ResourceType.class),
ArgumentMatchers.any(ActionType.class)))
.thenReturn(true);
}
但是,当我跑步时
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!auth.isAuthenticated()) { fail("NOT AUTHENTICATED!"); }
UsernamePasswordAuthenticationToken authToken =
(UsernamePasswordAuthenticationToken)auth;
mockMvc.perform(get("/health_secure")
.principal(auth)
.header("Authorization", "Bearer " + token))
.andDo(print())
.andExpect(status().isOk())
.andExpect(forwardedUrl("/actuator/health"));
我明白了:
"error":"invalid_token","error_description":"Cannot convert access token to JSON"
【问题讨论】:
-
您正在运行什么样的测试?
@Controller单元测试还是集成测试?
标签: java spring spring-boot spring-security mockmvc