@Test(expectedExceptions = BadCredentialsException.class) void testProviderAuthenticateWithInvalidTokenThrowsException() throws Exception { JwtTokenAuthenticationProvider provider = new JwtTokenAuthenticationProvider(signingKeyProvider, userDetailsService); JwtAuthenticationToken token = new JwtAuthenticationToken("invalid token"); provider.authenticate(token); }
@Test void testProviderSupportsJwtAuthToken() throws Exception { JwtTokenAuthenticationProvider provider = new JwtTokenAuthenticationProvider(signingKeyProvider, userDetailsService); boolean supported = provider.supports(JwtAuthenticationToken.class); assertTrue(supported); }
@Test(expectedExceptions = UsernameNotFoundException.class) void testProviderAuthenticateValidTokenButNonExistentUserThrowsException() throws Exception { String token = Jwts.builder() .setSubject("hacker") .signWith(SignatureAlgorithm.HS512, signingKeyProvider.getSigningKey()) .compact(); when(userDetailsService.loadUserByUsername(eq("hacker"))) .thenThrow(UsernameNotFoundException.class); JwtTokenAuthenticationProvider provider = new JwtTokenAuthenticationProvider(signingKeyProvider, userDetailsService); JwtAuthenticationToken authRequest = new JwtAuthenticationToken(token); provider.authenticate(authRequest); }
@Test void testProviderAuthenticatesOk() throws Exception { String token = Jwts.builder() .setSubject("admin") .signWith(SignatureAlgorithm.HS512, signingKeyProvider.getSigningKey()) .compact(); UserEntity user = new UserEntity("admin", "pw", Role.QUIZMASTER, true); user.setRoleType(Role.SUPERUSER); when(userDetailsService.loadUserByUsername(eq("admin"))).thenReturn(user); JwtTokenAuthenticationProvider provider = new JwtTokenAuthenticationProvider(signingKeyProvider, userDetailsService); JwtAuthenticationToken authRequest = new JwtAuthenticationToken(token); Authentication authResult = provider.authenticate(authRequest); assertNotNull(authResult); assertEquals(authResult.getPrincipal(), user); assertEquals(authResult.getCredentials(), token); assertTrue(authResult.isAuthenticated()); }