TokenAuthentication implements Authentication { @Override public boolean authenticate(@Nullable Credentials credentials) throws LoginException { if (credentials instanceof TokenCredentials) { TokenCredentials tc = (TokenCredentials) credentials; if (!validateCredentials(tc)) { throw new LoginException("Invalid token credentials."); } else { return true; } } return false; } TokenAuthentication(@NotNull TokenProvider tokenProvider); @Override boolean authenticate(@Nullable Credentials credentials); @Nullable @Override String getUserId(); @Nullable @Override Principal getUserPrincipal();  }
@Test public void testAuthenticateWithInvalidCredentials() throws Exception { List<Credentials> invalid = new ArrayList<>(); invalid.add(new GuestCredentials()); invalid.add(new SimpleCredentials(userId, new char[0])); for (Credentials creds : invalid) { assertFalse(authentication.authenticate(creds)); } }
@Test public void testAuthenticateWithInvalidTokenCredentials() { try { authentication.authenticate(new TokenCredentials(UUID.randomUUID().toString())); fail("LoginException expected"); } catch (LoginException e) { } }
@Test public void testAuthenticate() throws Exception { TokenInfo info = createTokenInfo(tokenProvider, userId); assertTrue(authentication.authenticate(new TokenCredentials(info.getToken()))); }
@Test public void testAuthenticateNotMatchingToken() { TokenInfo info = tokenProvider.createToken(userId, ImmutableMap.of(TokenConstants.TOKEN_ATTRIBUTE + "_mandatory", "val")); assertNotNull(info); try { authentication.authenticate(new TokenCredentials(info.getToken())); fail("LoginException expected"); } catch (LoginException e) { } }