dimanche 10 juin 2018

Testing the method with Spring Security authentication

I have a method

/**
 * {@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());
}

The method receives the ID of the logged in user during operation. Before performing the test, he performs

@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);
}

and I'm doing a test

/**
 * 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());
}

However, it turns out that ((CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId(); returned null, even though id I gave 1 in @Before.

Why can not I correctly set up an authorized user in Spring Security?

Aucun commentaire:

Enregistrer un commentaire