This is a continuation of this question Spring WebMvcTest how to mock Authentication?
I'm trying to test a controller method in Spring-boot that receives an Authentication
object as parameter. The controller is a RestController
with @CrossOrigin
annotation. The method looks like this:
@GetMapping("/authentication")
public String testAuthentication(Authentication authentication) {
UserDetailsStub userDetailsStub = (UserDetailsStub) authentication.getPrincipal();
return userDetailsStub.getUsername();
}
As you can see i get the principal from the Authentication out of the parameters.
The problem is, in my WebMvcTest
test case i get a NullPointerException
because in the test case, authentication
seems to be null. My question is why?
I have tried adding a given
call which will return a custom UserDetails
object in a @PostConstruct
annotated metho in the test case, but still i get the NullPointerException
.
My test case looks like this:
@Import(SecurityConfiguration.class)
@RunWith(SpringRunner.class)
@WebMvcTest(PDPController.class)
@AutoConfigureMockMvc(addFilters = false)
public class PDPControllerTests {
@Autowired
private MockMvc mvc;
@MockBean(name = "userDetailsService")
private MyUserDetailsService userDetailsService;
//..
@PostConstruct
public void setup() {
given(userDetailsService.loadUserByUsername(anyString()))
.willReturn(new UserDetailsStub());
}
//..
@Test
@WithUserDetails(value = "username", userDetailsServiceBeanName = "userDetailsService")
public void testAuthentication() throws Exception {
mvc.perform(get("/pdps/authentication").secure(true)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
Why is authentication
null in the test case, even when i supply it in the @PostConstruct
method?
A GitHub project with minimal code that reproduces the error can be found here. https://github.com/Kars1090/SpringSecurityTest
Thanks!
After clone your project I have achieved to receive a valid Authentication
object in your controller method. Basically you have 2 main problems in your test:
JwtRequestFilter
In summary, the changes were the following ones:
public class UserDetailsStub implements UserDetails {
private String username;
private String password;
private Collection<? extends GrantedAuthority> authorities;
public UserDetailsStub() {}
public static UserDetailsStub of (User user) {
UserDetailsStub userDetails = new UserDetailsStub();
if (null != user) {
userDetails.username = user.getUsername();
userDetails.password = user.getPassword();
userDetails.authorities = user.getAuthorities();
}
return userDetails;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
// Rest of the code is equal to your version
Your controller method:
@GetMapping("/authentication")
public String testAuthentication(Authentication authentication) {
UserDetailsStub userDetailsStub = UserDetailsStub.of((User)
authentication.getPrincipal());
return userDetailsStub.getUsername();
}
And the test:
@WebMvcTest(value = PDPController.class)
public class PDPControllerTests {
@Autowired
private MockMvc mvc;
/** You have not to mock the filter because in that case Spring
* won't know how to deal with it, when the list of them
* should be managed.
*
* That is the reason why you had to include
* @AutoConfigureMockMvc(addFilters = false), but that
* is preciselly what was avoiding the creation of your
* Authentication object, because your JwtRequestFilter
* was not being executed.
*
* With the current code, your filter will be executed and
* the Authentication object created.
*/
//@MockBean
//private JwtRequestFilter jwtRequestFilter;
// What you have to mock are the classes the filter uses internally
@MockBean
private MyUserDetailsService userDetailsService;
@MockBean
private JwtService jwtService;
@Test
@WithMockUser
public void test() throws Exception {
mvc.perform(
get("/pdps/authentication").secure(true)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With