使用Spring Security身份验证测试方法

时间:2018-06-10 14:08:03

标签: java spring spring-mvc spring-boot testing

我有一个方法

/**
 * {@inheritDoc}
 */
@Override
public List<User> getInvitations() throws ResourceNotFoundException {
    log.info("Called with outgoing {}", outgoing);

    final String id = ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();

    return this.findUser(id).getSentInvitations()
            .stream()
            .map(ServiceUtils::toUserDto)
            .collect(Collectors.toList());
}

该方法在操作期间接收登录用户的ID。在进行测试之前,他执行

@Before
public void setup() {
    final Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    grantedAuthorities.add(new SimpleGrantedAuthority(SecurityRole.ROLE_USER.toString()));

    Authentication authentication
            = new UsernamePasswordAuthenticationToken(
                    new CustomUserDetails(
                            UUID.randomUUID().toString(),
                            UUID.randomUUID().toString(),
                            grantedAuthorities,
                            "1"
                    ), null);
    SecurityContext sc = SecurityContextHolder.getContext();
    sc.setAuthentication(authentication);
}

我正在做一个测试

/**
 * Test the getInvitations method.
 */
@Test
public void canGetInvitations() {
    final String id = "1";
    final UserEntity entity = Mockito.mock(UserEntity.class);
    Mockito
            .when(this.userRepository.findByUniqueIdAndEnabledTrue(id))
            .thenReturn(Optional.of(entity));
    Assert.assertTrue(this.userSearchService.getInvitations().isEmpty());
}

然而,事实证明,((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();返回了null,即使id我在1中提供了@Before

为什么我无法在Spring Security中正确设置授权用户?

0 个答案:

没有答案