spring-mvcspring-securityspring-bootspring-test-mvc

@WithMockUser ignores username, password fields?


I'm using @WithMockUser to test a controller method secured with basic auth in a simple spring boot web service. My annotation looks like:

@WithMockUser(username = 'admin', password = 'mypassword', roles = ['ADMIN'])

It seems however that the username and password field are ignored. The test passes even if I specify an incorrect username or password. The roles field however does appear to be used and the test fails with an invalid role is provided.

Perhaps I'm misunderstanding the role of this annotation, but should I be able to use it to verify behavior of incorrect credentials being supplied to a secured method?

Thanks!

--john


Solution

  • If you are using Spring MVC Test (i.e., MockMvc), you would do something like the following:

    mvc.perform(get("/").with(httpBasic("user","password"))) // ...
    

    This is documented in the Testing HTTP Basic Authentication section of the Spring Security reference manual.

    If you have configured your test to launch Spring Boot with an embedded Servlet container, you can use Spring Boot's TestRestTemplate which supports "Basic HTTP authentication (with a username and password)".