Spring boot 手动Spring安全登录的集成测试
我正在尝试对我的手动Spring安全登录进行集成测试。以下是测试等级:Spring boot 手动Spring安全登录的集成测试,spring-boot,spring-security,integration-testing,security-context,Spring Boot,Spring Security,Integration Testing,Security Context,我正在尝试对我的手动Spring安全登录进行集成测试。以下是测试等级: @RunWith(SpringRunner.class) @ContextConfiguration @WebAppConfiguration @SpringBootTest @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) class UserIT { private MockMvc mockMvc; @Autow
@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());
}
}
当我尝试通过Postman调用端点时,一切都正常工作,但是在测试中,SecurityContext不知何故丢失并返回ROLE_ANONYMOUS而不是ROLE_USER。我是否在测试类中丢失了一些注释,或者只是因为我无法对手动登录进行集成测试
提前谢谢 调用
mockMvc.perform(get(“/user/authority/”)
不会将登录的会话信息传递给服务器。因此,服务器会处理来自未经身份验证的用户的请求。这就是为什么您会获得角色\u匿名的原因。非常感谢!!我刚刚将会话作为模拟调用的变量传递,它工作了!!
@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!");
}
}
}