认证成功后,我将认证的用户保存在一个会话中。之后,我使用@SessionAttributes(" user ")在任何控制器中检索用户。
现在我正在试着测试它:
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = SpringSecurityTestConfig.class
)
public class ProfileMetaDataControllerTest {
private MockMvc mockMvc;
@Autowired
private MyController myController;
@Autowired
private WebApplicationContext context;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(myController).build();
}
@Test
@WithUserDetails("userMail@hotmail.com")
public void shouldReturnDefaultMessage() throws Exception {
String expectedValue ="greeting";
MvcResult result = this.mockMvc.perform(get("/contentUrl")
.contentType(MediaType.TEXT_PLAIN)
.content("romakapt@gmx.de"))
.andDo(print())
.andExpect(content().string(expectedValue))
.andReturn();
}
}和我的控制器,这将被测试:
@RestController
@RequestMapping("/profile")
@SessionAttributes("user")
public class ProfileMetaDataController {
@GetMapping("/contentUrl")
@ResponseBody
public List<String> getInformation(Model model) throws IOException {
User user = Optional.ofNullable((User) model.asMap().get("user")); //User ist null!!!!
}
}User为空,因为我的AuthenticationSuccessHandler从不调用onAuthenticationSuccess方法,我在会话中存储user。
我该怎么处理呢?通常UsernamePasswordAuthenticationFilter会调用我的AuthenticationSuccessHandler,但不会在MockMVC测试期间调用。
发布于 2019-06-20 16:40:21
如果没有其他原因,请不要使用@SessionAttributes。通常,身份验证用户存储在SecurityContextHolder中,如下所示:
SecurityContextHolder.getContext().getAuthentication().getPrincipal()如果你想在控制器上获得用户,试试这3件事。
public List<String> getInformation(@AuthenticationPrincipal YourUser youruser) {
// ...
}
public List<String> getInformation(Principal principal) {
YourUser youruser = (YourUser) principal;
// ...
}
public List<String> getInformation(Authentication authentication) {
YourUser youruser = (YourUser) authentication.getPrincipal();
// ...
}https://stackoverflow.com/questions/56676395
复制相似问题