Spring 安全 AuthenticationSuccessHandler 和 MockMvc

Spring Security AuthenticationSuccessHandler and MockMvc

成功验证后,我在会话中保存了经过验证的用户。 之后,我使用 @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!!!!
    }
}

用户为空,因为我的 AuthenticationSuccessHandler 从不调用我在会话中存储用户的 onAuthenticationSuccess 方法。

我该如何处理? 通常 UsernamePasswordAuthenticationFilter 会调用我的 AuthenticationSuccessHandler,但不会在 MockMVC 测试期间调用。

如果没有其他原因,请不要使用@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();
    // ...
}