October 22, 2024
Chicago 12, Melborne City, USA
java

Authentication is null despite @WithMockUser


I have this controller where it retrieve the user authentication data and print them out.

@GetMapping("/get-role")
public ResponseEntity<String> getRole(Authentication auth) {
    String role = auth.getAuthorities().stream().findFirst().get().toString();
    return ResponseEntity.ok(role);
}

The problem comes when I tried to write the unit test

@Test
@DisplayName("Test Role")
@WithMockUser (username = "user", roles = {"Admin"})
void testRole() throws Exception {
    URI uri = new URI("/v1/me/get-role");
    mockRequest
            .perform(MockMvcRequestBuilders.get(uri))
            .andExpect(MockMvcResultMatchers.status().isOk());
}

The error says:

jakarta.servlet.ServletException: 
    Request processing failed: 
    java.lang.NullPointerException: 
    Cannot invoke "org.springframework.security.core.Authentication.getAuthorities()" because "auth" is null

If you’re wondering about my pom.xml, I’ve included these:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

I’ve also included these on top of my test class

@WebMvcTest(controllers = MyController.class)
@AutoConfigureMockMvc(addFilters = false)
@ContextConfiguration(classes = SecurityConfig.class)
@Import(MyController.class)
public class MyControllerTest {
// rest of code
}

I’ve tried many solutions in the internet, such as

User mockUser = Mockito.mock(User.class);
Authentication authentication = Mockito.mock(UsernamePasswordAuthenticationToken.class);

Mockito.when(authentication.getPrincipal()).thenReturn(mockUser);
Mockito.when(authentication.getCredentials()).thenReturn("password");
Mockito.when(authentication.isAuthenticated()).thenReturn(true);
Mockito.when(authentication.getAuthorities()).thenReturn((Collection) List.of(new SimpleGrantedAuthority("Admin")));
mockRequest
     .perform(MockMvcRequestBuilders
         .get(uri)
         .with(SecurityMockMvcRequestPostProcessors
            .user("user")
            .authorities(new SimpleGrantedAuthority("Admin"))))
      .andExpect(MockMvcResultMatchers.status().isOk());

And this solution below gave me different error

mockRequest
     .perform(MockMvcRequestBuilders
         .get(uri)
         .with(SecurityMockMvcRequestPostProcessors.jwt()))
      .andExpect(MockMvcResultMatchers.status().isOk());
java.lang.NoClassDefFoundError: 
    org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverter

If you need more information, feel free to add some comment.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video