I am trying to do an integration test for my manual Spring Security Login. Below is the test class:
@RunWith(SpringRunner.class)
@ContextConfiguration
@WebAppConfiguration
@SpringBootTest
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
class UserIT {
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private UserService userService;
@Autowired
private WebApplicationContext context;
@Autowired
private TestRestTemplate restTemplate;
@LocalServerPort
private int port;
UserDTO userDTO = new UserDTO();
String username = "user";
Authorities userAuthorities = new Authorities();
Set<Authorities> grantedAuthorities = new HashSet<>();
@BeforeEach
void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
userDTO.setUsername(username);
userDTO.setPassword(username);
userAuthorities.setUsername(username);
userAuthorities.setAuthority("ROLE_USER");
grantedAuthorities.add(userAuthorities);
userDTO.setAuthorities(grantedAuthorities);
}
@Test
void userLogin() throws Exception {
mockMvc.perform(post("/user/register/")
.contentType("application/json")
.content(objectMapper.writeValueAsString(userDTO)))
.andExpect(status().isOk());
mockMvc.perform(post("/user/login/")
.contentType("application/json")
.content(objectMapper.writeValueAsString(userDTO)))
.andExpect(status().isOk());
Collection<GrantedAuthority> authorities = new HashSet<>();
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
authorities.add(simpleGrantedAuthority);
MvcResult mvcResult = mockMvc.perform(get("/user/authority/")
.contentType("application/json"))
.andReturn();
assertEquals(authorities, mvcResult.getResponse().getContentAsString());
}
}
The issue is that mvcResult.getResponse().getContentAsString()
returns a collection of ROLE_ANONYMOUS instead of ROLE_USER, since I am calling the login endpoint with a ROLE_USER authority user.
Below is my UserService class:
@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final AuthenticationManager authenticationManager;
public UserDetails loadUserByUsername(String username){
Users user = userRepository.findByUsername(username);
if (user == null)
throw new UsernameNotFoundException("Username Not Found");
UserDetails springUser =
org.springframework.security.core.userdetails.User.builder()
.authorities(this.getAuthorities(user))
.username(username)
.password(user.getPassword())
.build();
return springUser;
}
public Collection<? extends GrantedAuthority> getAuthoritiesFromContext(){
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)
SecurityContextHolder.getContext().getAuthentication().getAuthorities();
return authorities;
}
public Collection<? extends GrantedAuthority> getAuthorities(Users user){
Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
user.getAuthorities().forEach(authority ->
authorities.add(new SimpleGrantedAuthority(authority.getAuthority())));
return authorities;
}
public Users saveUser(UserDTO userDTO){
Users user = new Users(userDTO.getUsername(), userDTO.getPassword(),
userDTO.getAuthorities());
return userRepository.save(user);
}
public UserDetails login(UserDTO userDTO){
UserDetails userDetails = this.loadUserByUsername(userDTO.getUsername());
if(userDetails.getPassword().equals(userDTO.getPassword())){
Authentication authentication =
new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDTO.getPassword(), userDetails.getAuthorities());
authentication = authenticationManager.authenticate(authentication);
SecurityContextHolder.getContext().setAuthentication(authentication);
return userDetails;
} else {
throw new BadCredentialsException("Username and password do not match!");
}
}
}
When I try calling the endpoints through Postman it all works correctly, however in the test, somehow the SecurityContext gets lost and returns ROLE_ANONYMOUS instead of ROLE_USER. Am I missing some annotation in the test class, or is it just that I cannot do an integration test for my manual login?
Thanks in advance!!