我正在尝试为我的手动 Spring Security Login 进行集成测试。下面是测试类:
@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());
}
}
问题是mvcResult.getResponse().getContentAsString()返回 ROLE_ANONYMOUS 而不是 ROLE_USER 的集合,因为我使用 ROLE_USER 权限用户调用登录端点。
下面是我的 UserService 类:
@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!");
}
}
}
当我尝试通过 Postman 调用端点时,一切正常,但是在测试中,SecurityContext 不知何故丢失并返回 ROLE_ANONYMOUS 而不是 ROLE_USER。我是否在测试类中遗漏了一些注释,或者只是我无法为手动登录进行集成测试?
提前致谢!!