Problem z testem integracyjnym serwisu uwierzytelniania w Spring-boot

0

Chcę napisać test dla funkcji uwierzytelniania logowania z serwisu:

    public AuthenticationResponse login(LoginRequest loginRequest) throws Exception {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);

        String token = jwtProvider.generateToken(authentication);

        boolean admin = false;
        if(authentication.getAuthorities().stream().anyMatch(ga -> ga.getAuthority().equals("ROLE_ADMIN"))) {
            admin = true;
        }

        return new AuthenticationResponse(token, loginRequest.getUsername(), admin);
    }

Problem leży w tym że nie wiem jak sprawić żeby authenticationManager.authenticate zwracał mi jakiś obiekt.
Mój test wygląda na razie w ten sposób:

@Test
    public void login_Success() throws Exception {
        // args
        LoginRequest loginRequest = new LoginRequest("Quokka", "tajnaQuokka");

        // when
        Mockito.when(jwtProvider.generateToken(Mockito.any())).thenAnswer(i -> token);

        // call
        AuthenticationResponse response = authService.login(loginRequest);

        // tests
        assertEquals(response, new AuthenticationResponse(token, loginRequest.getUsername(), false));
    }

i działał dopóki nie postanowiłem do aplikacji dodać roli admina i zacząłem sprawdzać zawartości 'authentication' w ifie:

java.lang.NullPointerException: Cannot invoke "org.springframework.security.core.Authentication.getAuthorities()" because "authentication" is null
1
  1. Nie do końca rozumiem co ty tu robisz. Ty chcesz generować token JWT? To czemu robisz jakieś SecurityContextHolder.getContext().setAuthentication(authentication);? Trochę to dziwne. Generujesz token, odsyłasz a potem requesty niech są zabezpieczone przez spring security i sprawdzanie tokenu
  2. Trochę dziwnie tą asercje robisz. Czemu nie wyciągniesz tokena z responsa i nie porównasz, zamiast próbować zbudować AuthenticationResponse?
  3. Trudno cokolwiek powiedzieć nie wiedząc co to w ogole za authenticationManager
0

@Shalom:
3. Implementuję UserDetailsService który nadaje role o które pytasz:

@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final UserRepository userRepository;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) {
        Optional<User> userOptional = userRepository.findByUsername(username);
        User user = userOptional.orElseThrow(() -> new UsernameNotFoundException("No user " +
                        "found with username : " + username));
        if(!user.isAdmin()) {
            return new org.springframework.security.core
                    .userdetails.User(user.getUsername(), user.getPassword(),
                    user.isEnabled(), true, true,
                    true, getAuthorities("ROLE_USER"));
        }
        else {
            return new org.springframework.security.core
                    .userdetails.User(user.getUsername(), user.getPassword(),
                    user.isEnabled(), true, true,
                    true, getAuthorities("ROLE_ADMIN"));
        }
    }

    private Collection<? extends GrantedAuthority> getAuthorities(String role) {
        return singletonList(new SimpleGrantedAuthority(role));
    }
}

0

No ok, a jak zapniesz sie debugerem po tym authenticationManager.authenticate to na pewno nie ma tam nigdzie tych authorities?

1 użytkowników online, w tym zalogowanych: 0, gości: 1