Reputation: 599
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
Upvotes: 2
Views: 1607
Reputation: 1
This has happened to me as well. I think @WithMockUser is enough to test secured services. user/password/roles is not required. I validated this scenario in my case.
Upvotes: 0
Reputation: 31227
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)".
Upvotes: 2