io.dropwizard.auth.AuthenticationException Java Examples
The following examples show how to use
io.dropwizard.auth.AuthenticationException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TenacityAuthenticatorTest.java From tenacity with Apache License 2.0 | 6 votes |
@Test(expected = HystrixRuntimeException.class) public void shouldThrowWhenAuthenticateTimesOut() throws AuthenticationException { final TenacityConfiguration overrideConfiguration = new TenacityConfiguration(); overrideConfiguration.setExecutionIsolationThreadTimeoutInMillis(1); new TenacityPropertyRegister( ImmutableMap.of(DependencyKey.TENACITY_AUTH_TIMEOUT, overrideConfiguration), new BreakerboxConfiguration(), mock(ArchaiusPropertyRegister.class)) .register(); when(mockAuthenticator.authenticate(any(BasicCredentials.class))).thenAnswer((invocation) -> { Thread.sleep(50); return new Object(); }); try { assertThat(tenacityAuthenticator.authenticate(new BasicCredentials("credentials", "credentials"))) .isEqualTo(Optional.empty()); } catch (HystrixRuntimeException err) { assertThat(err.getFailureType()).isEqualTo(HystrixRuntimeException.FailureType.TIMEOUT); throw err; } }
Example #2
Source File: AbstractAuthResource.java From robe with GNU Lesser General Public License v3.0 | 6 votes |
/** * Ensures that the password meets site-specific complexity requirements, like length or number * of character sets. This method takes the old password so that the algorithm can analyze the * new password to see if it is too similar to the old password. Note that this has to be * invoked when the user has entered the old password, as the list of old * credentials stored by ESAPI is all hashed. * Additionally, the user object is taken in order to verify the password and account name differ. * * @param oldPassword the old password * @param newPassword the new password * @param user the user * @throws io.dropwizard.auth.AuthenticationException if newPassword is too similar to oldPassword or if newPassword does not meet complexity requirements */ public void verifyPasswordStrength(String oldPassword, String newPassword, T user) throws AuthenticationException { List<Rule> rules = getPasswordRules(); PasswordValidator validator = new PasswordValidator(rules); PasswordData passwordData = new PasswordData(new Password(newPassword)); RuleResult result = validator.validate(passwordData); if (!result.isValid()) { StringBuilder messages = new StringBuilder(); for (String msg : validator.getMessages(result)) { messages.append(msg).append("\n"); } throw new AuthenticationException(messages.toString()); } }
Example #3
Source File: CachingJwtAuthenticator.java From dropwizard-auth-jwt with Apache License 2.0 | 6 votes |
@Override public Optional<P> authenticate(JwtContext context) throws AuthenticationException { final Timer.Context timer = gets.time(); try { final SimpleEntry<JwtContext, Optional<P>> cacheEntry = cache.getIfPresent(context.getJwt()); if (cacheEntry != null) { return cacheEntry.getValue(); } cacheMisses.mark(); final Optional<P> principal = authenticator.authenticate(context); if (principal.isPresent()) { cache.put(context.getJwt(), new SimpleEntry<>(context, principal)); } return principal; } finally { timer.stop(); } }
Example #4
Source File: AuthUtil.java From dropwizard-auth-jwt with Apache License 2.0 | 6 votes |
public static Authenticator<JwtContext, Principal> getJWTAuthenticator(final List<String> validUsers) { return context -> { try { final String subject = context.getJwtClaims().getSubject(); if (validUsers.contains(subject)) { return Optional.of(new PrincipalImpl(subject)); } if ("bad-guy".equals(subject)) { throw new AuthenticationException("CRAP"); } return Optional.empty(); } catch (MalformedClaimException e) { return Optional.empty(); } }; }
Example #5
Source File: JsonWebTokenAuthenticatorTest.java From jobson with Apache License 2.0 | 6 votes |
/** * Test that .authenticate does not throw an error when provided with * a valid JWT token. */ @Test public void testAuthenticateDoesNotThrowWHenProvidedWithAValidJWTToken() throws AuthenticationException { final Key secretKey = createSecretKey(); final SignatureAlgorithm signatureAlgorithm = getValidSignatureAlgorithm(); final Principal principal = generatePrincipal(); final String jwt = createJwtToken(signatureAlgorithm, secretKey, principal); final JsonWebTokenAuthenticator authenticator = createAuthenticator(secretKey, signatureAlgorithm); // Shouldn't throw, because we created a valid jwt token // using the same secret key as the authenticator. authenticator.authenticate(jwt); }
Example #6
Source File: CachingAuthenticator.java From dropwizard-java8 with Apache License 2.0 | 6 votes |
@Override public Optional<P> authenticate(C credentials) throws AuthenticationException { final Timer.Context context = gets.time(); try { Optional<P> optionalPrincipal = cache.getIfPresent(credentials); if (optionalPrincipal == null) { cacheMisses.mark(); optionalPrincipal = underlying.authenticate(credentials); if (optionalPrincipal.isPresent()) { cache.put(credentials, optionalPrincipal); } } return optionalPrincipal; } finally { context.stop(); } }
Example #7
Source File: JsonWebTokenAuthenticatorTest.java From jobson with Apache License 2.0 | 6 votes |
/** * Test that .authenticate does throw when provided with a valid * JWT created with a different secret key. */ @Test(expected = AuthenticationException.class) public void testAuthenticateThrowsWhenProvidedWithAValidJWTCreatedFromADifferentSecretKey() throws AuthenticationException { final Key jwtKey = createSecretKey(); final SignatureAlgorithm signatureAlgorithm = getValidSignatureAlgorithm(); final Principal principal = generatePrincipal(); final String jwt = createJwtToken(signatureAlgorithm, jwtKey, principal); final Key authenticatorKey = createSecretKey(); final JsonWebTokenAuthenticator authenticator = createAuthenticator(authenticatorKey, signatureAlgorithm); // Should throw because jwt was created with a different secret // key. authenticator.authenticate(jwt); }
Example #8
Source File: JsonWebTokenAuthenticatorTest.java From jobson with Apache License 2.0 | 6 votes |
/** * Test that .authenticate returns the provided (JWT-encoded) user * principal upon success. */ @Test public void testAuthenticateReturnsTheProvidedJWTEncodedUserPricipalUponSuccess() throws AuthenticationException { final Key key = createSecretKey(); final SignatureAlgorithm signatureAlgorithm = getValidSignatureAlgorithm(); final Principal providedPrincipal = generatePrincipal(); final String jwt = createJwtToken(signatureAlgorithm, key, providedPrincipal); final JsonWebTokenAuthenticator authenticator = createAuthenticator(key, signatureAlgorithm); final Optional<Principal> possibleAuthenticatedPrincipal = authenticator.authenticate(jwt); Assertions.assertThat(possibleAuthenticatedPrincipal).isNotNull(); assertThat(possibleAuthenticatedPrincipal.isPresent()).isTrue(); final Principal authenticatedPrincipal = possibleAuthenticatedPrincipal.get(); assertThat(authenticatedPrincipal).isNotNull(); assertThat(authenticatedPrincipal).isEqualTo(providedPrincipal); }
Example #9
Source File: AbstractAuthResource.java From robe with GNU Lesser General Public License v3.0 | 6 votes |
/** * Changes the password for the specified user. This requires the current password, as well as * the password to replace it with. The new password should be checked against old hashes to be sure the new password does not closely resemble or equal any recent passwords for that UserEntry. * Password strength should also be verified. This new password must be repeated to ensure that the user has typed it in correctly. * * @param user the user to change the password for * @param currentPassword the current password for the specified user * @param newPassword the new password to use * @param newPassword2 a verification copy of the new password * @throws io.dropwizard.auth.AuthenticationException if any errors occur */ public void changePassword(T user, String currentPassword, String newPassword, String newPassword2) throws AuthenticationException { verifyPassword(user, currentPassword); if (!newPassword.equals(newPassword2)) { throw new AuthenticationException(user.getUsername() + ": New password and re-type password must be same"); } else if (newPassword.equals(currentPassword)) { throw new AuthenticationException(user.getUsername() + ": New password and old password must be different"); } verifyPasswordStrength(currentPassword, newPassword, user); Optional<? extends UserEntry> optional = userStore.changePassword(user.getUsername(), newPassword); if (!optional.isPresent()) { throw new AuthenticationException(user.getUsername() + ": Can't update UserEntry Password"); } }
Example #10
Source File: AuthenticatedWebSocket.java From robe with GNU Lesser General Public License v3.0 | 6 votes |
@Override public String onConnect(Session session) { for (HttpCookie cookie : session.getUpgradeRequest().getCookies()) { if ("auth-token".equals(cookie.getName())) { String authToken = cookie.getValue(); TokenAuthenticator authenticator = getAuthenticator(); org.hibernate.Session hSession = sessionFactory.openSession(); ManagedSessionContext.bind(hSession); Optional<BasicToken> token; try { token = authenticator.authenticate(authToken); } catch (AuthenticationException e) { e.printStackTrace(); return null; } if (!token.isPresent()) { return null; } hSession.close(); return token.get().getUserId(); } } return null; }
Example #11
Source File: ThirdEyeLdapAuthenticator.java From incubator-pinot with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} */ @Override public Optional<ThirdEyePrincipal> authenticate(ThirdEyeCredentials credentials) throws AuthenticationException { try { if (StringUtils.isNotBlank(credentials.getToken())) { SessionDTO sessionDTO = this.sessionDAO.findBySessionKey(credentials.getToken()); if (sessionDTO != null && System.currentTimeMillis() < sessionDTO.getExpirationTime()) { return Optional.of(new ThirdEyePrincipal(credentials.getPrincipal(), credentials.getToken())); } } String username = credentials.getPrincipal(); String password = credentials.getPassword(); if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) { LOG.info("Unable to authenticate empty user name/password"); return Optional.empty(); } else { return ldapAuthenticate(username, password); } } catch (Exception e) { throw new AuthenticationException(e); } }
Example #12
Source File: BcryptAuthenticator.java From keywhiz with Apache License 2.0 | 6 votes |
@Override public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException { User user = null; String username = credentials.getUsername(); if (!User.isSanitizedUsername(username)) { logger.info("Username: {} must match pattern: {}", username, User.USERNAME_PATTERN); return Optional.empty(); } // Get hashed password column from BCrypt table by username & verify hash against plaintext String password = credentials.getPassword(); Optional<String> optionalHashedPwForUser = userDAO.getHashedPassword(username); if (checkPassword(password, optionalHashedPwForUser)) { user = User.named(username); } return Optional.ofNullable(user); }
Example #13
Source File: TenacityAuthenticatorTest.java From tenacity with Apache License 2.0 | 6 votes |
@Test public void shouldNotTransformAuthenticationExceptionIntoMappedException() throws AuthenticationException { when(AuthenticatorApp.getMockAuthenticator().authenticate(any(BasicCredentials.class))).thenThrow(new AuthenticationException("test")); final Client client = new JerseyClientBuilder(new MetricRegistry()) .using(executorService, Jackson.newObjectMapper()) .build("dropwizard-app-rule"); client.register(HttpAuthenticationFeature.basicBuilder() .nonPreemptive() .credentials("user", "stuff") .build()); final Response response = client .target(URI.create("http://localhost:" + RULE.getLocalPort() + "/auth")) .request() .get(Response.class); assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); verify(AuthenticatorApp.getMockAuthenticator(), times(1)).authenticate(any(BasicCredentials.class)); verifyZeroInteractions(AuthenticatorApp.getTenacityContainerExceptionMapper()); verify(AuthenticatorApp.getTenacityExceptionMapper(), times(1)).toResponse(any(HystrixRuntimeException.class)); }
Example #14
Source File: ExceptionLoggingCommandHookIntegrationTest.java From tenacity with Apache License 2.0 | 6 votes |
@Test public void shouldNotLogWhenShortCircuited() { final DefaultExceptionLogger defaultExceptionLogger = spy(new DefaultExceptionLogger()); HystrixPlugins.getInstance().registerCommandExecutionHook(new ExceptionLoggingCommandHook(defaultExceptionLogger)); try { new AlwaysShortCircuit().execute(); } catch (HystrixRuntimeException err) { assertThat(Throwables.getCausalChain(err) .stream() .filter(AuthenticationException.class::isInstance) .findAny()) .isNotEmpty(); } verifyZeroInteractions(defaultExceptionLogger); }
Example #15
Source File: AuthUtil.java From dropwizard-java8 with Apache License 2.0 | 5 votes |
public static Authenticator<BasicCredentials, Principal> getBasicAuthenticator(final List<String> validUsers) { return credentials -> { if (validUsers.contains(credentials.getUsername()) && "secret".equals(credentials.getPassword())) { return Optional.<Principal>of(new PrincipalImpl(credentials.getUsername())); } if ("bad-guy".equals(credentials.getUsername())) { throw new AuthenticationException("CRAP"); } return Optional.empty(); }; }
Example #16
Source File: ThirdEyeAuthenticatorLdapTest.java From incubator-pinot with Apache License 2.0 | 5 votes |
@Test public void testBlankAuthentication() { // Failed reason: blank username try { credentials = new ThirdEyeCredentials(null, PASSWORD); Optional<ThirdEyePrincipal> authenticate = thirdEyeAuthenticatorLdap.authenticate(credentials); Assert.assertFalse(authenticate.isPresent(), "Authentication should fail!"); } catch (AuthenticationException e) { LOG.warn("Exception during authentication.", e); Assert.fail(); } }
Example #17
Source File: ResourceAuthenticator.java From dropwizard-auth-ldap with Apache License 2.0 | 5 votes |
@Override public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException { if (ldapAuthenticator.authenticate(credentials)) { return Optional.of(new User(credentials.getUsername(), Collections.emptySet())); } else { return Optional.empty(); } }
Example #18
Source File: LdapHealthCheck.java From dropwizard-auth-ldap with Apache License 2.0 | 5 votes |
@Override public Result check() throws AuthenticationException { if (ldapAuthenticator.authenticate(new BasicCredentials("", "")).isPresent()) { return Result.healthy(); } else { return Result.unhealthy("Cannot contact authentication service"); } }
Example #19
Source File: TenacityContainerExceptionMapperTest.java From tenacity with Apache License 2.0 | 5 votes |
@Test(expected = InternalServerErrorException.class) public void exceptionsShouldNotMap() throws AuthenticationException { when(mockAuthenticator.authenticate(anyString())).thenThrow(new RuntimeException()); resources.client() .target("/") .request() .header(HttpHeaders.AUTHORIZATION, "Bearer TEST") .get(String.class); }
Example #20
Source File: TenacityContainerExceptionMapperTest.java From tenacity with Apache License 2.0 | 5 votes |
@Test public void exceptionsShouldMapTimeouts() throws AuthenticationException { Optional<Integer> responseStatus; try { final TenacityConfiguration timeoutConfiguration = new TenacityConfiguration(); timeoutConfiguration.setExecutionIsolationThreadTimeoutInMillis(1); new TenacityPropertyRegister( ImmutableMap.of(DependencyKey.TENACITY_AUTH_TIMEOUT, timeoutConfiguration), new BreakerboxConfiguration()) .register(); when(mockAuthenticator.authenticate(anyString())).thenAnswer((invocation) -> { Thread.sleep(100); return Optional.empty(); }); final Response response = resources.client() .target("/") .request() .header(HttpHeaders.AUTHORIZATION, "Bearer TEST") .get(Response.class); responseStatus = Optional.of(response.getStatus()); } catch (ResponseProcessingException err) { responseStatus = Optional.of(err.getResponse().getStatus()); } assertThat(responseStatus).contains(statusCode); }
Example #21
Source File: TenacityContainerExceptionMapperTest.java From tenacity with Apache License 2.0 | 5 votes |
@Test(expected = InternalServerErrorException.class) public void authenticationExceptions() throws AuthenticationException { when(mockAuthenticator.authenticate(anyString())).thenThrow(new AuthenticationException("auth error")); resources.client() .target("/") .request() .header(HttpHeaders.AUTHORIZATION, "Bearer TEST") .get(String.class); }
Example #22
Source File: ThirdEyeAuthenticatorLdapTest.java From incubator-pinot with Apache License 2.0 | 5 votes |
@Test public void testFailedAuthentication() { // Failed reason: username 3 doesn't exist in domain1 and domain2 try { credentials = new ThirdEyeCredentials(USERNAME3, PASSWORD); Optional<ThirdEyePrincipal> authenticate = thirdEyeAuthenticatorLdap.authenticate(credentials); Assert.assertFalse(authenticate.isPresent(), "Authentication should fail!"); } catch (AuthenticationException e) { LOG.warn("Exception during authentication.", e); Assert.fail(); } }
Example #23
Source File: SimpleBasicAuthenticatorTest.java From eagle with Apache License 2.0 | 5 votes |
@Test public void testUnexistingUsername() { try { Optional<User> result = authenticator.authenticate(new BasicCredentials(TEST_UNEXISTING_USERNAME, TEST_SECRET_PHRASE)); Assert.assertFalse("result is present when passed unexisting username", result.isPresent()); } catch (AuthenticationException e) { Assert.fail("unexpected error occurs: " + e.getMessage()); } }
Example #24
Source File: AbstractKeycloakAuthenticator.java From keycloak-dropwizard-integration with Apache License 2.0 | 5 votes |
@Override public Optional<P> authenticate(HttpServletRequest request) throws AuthenticationException { KeycloakSecurityContext securityContext = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName()); if (securityContext != null) { return Optional.ofNullable(prepareAuthentication(securityContext, request, keycloakConfiguration)); } else { return Optional.empty(); } }
Example #25
Source File: SimpleBasicAuthenticatorTest.java From eagle with Apache License 2.0 | 5 votes |
@Test public void testWrongPassword() { try { Optional<User> result = authenticator.authenticate(new BasicCredentials(TEST_USERNAME, TEST_WRONG_SECRET_PHRASE)); Assert.assertFalse("result is present when passed wrong password", result.isPresent()); } catch (AuthenticationException e) { Assert.fail("unexpected error occurs: " + e.getMessage()); } }
Example #26
Source File: FacebookTokenAuthenticator.java From microservices-comparison with Apache License 2.0 | 5 votes |
@Override public Optional<User> authenticate(String token) throws AuthenticationException { Try<User> user = accessTokenVerificationCommandFactory.createVerificationCommand(token).executeCommand(); return user.toJavaOptional() .map(Optional::of) .orElse(Optional.absent()); }
Example #27
Source File: SapBasicAuthenticator.java From SAPNetworkMonitor with GNU General Public License v3.0 | 5 votes |
public Optional<BasicAuthUser> authenticate(BasicCredentials credentials) throws AuthenticationException { Optional<User> optionalUser = authService.validateUser(credentials.getUsername(), credentials.getPassword()); if (optionalUser.isPresent()) { User user = optionalUser.get(); return Optional.of(BasicAuthUser.builder() .userId(user.getUserId()) .accountId(user.getAccountId()) .name(user.getName()) .loginName(user.getLoginName()) .build()); } return Optional.empty(); }
Example #28
Source File: KeycloakAuthFilter.java From keycloak-dropwizard-integration with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestContext) { validateRequest(requestContext); HttpServletRequest request = (HttpServletRequest) requestContext.getProperty(HttpServletRequest.class.getName()); final Optional<P> principal; try { principal = authenticator.authenticate(request); if (principal.isPresent()) { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return principal.get(); } @Override public boolean isUserInRole(String role) { return authorizer.authorize(principal.get(), role); } @Override public boolean isSecure() { return requestContext.getSecurityContext().isSecure(); } @Override public String getAuthenticationScheme() { return SecurityContext.BASIC_AUTH; } }); return; } } catch (AuthenticationException e) { LOGGER.warn("Error authenticating credentials", e); throw new InternalServerErrorException(); } // TODO: re-enable / check if 302 has been returned // throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm)); }
Example #29
Source File: BasicCredentialAuthFilterTest.java From dropwizard-simpleauth with Apache License 2.0 | 5 votes |
@Override public Optional<String> authenticate(BasicCredentials credentials) throws AuthenticationException { if (credentials.getUsername().equals("user") && credentials.getPassword().equals("foo")) { return Optional.of("user"); } return Optional.empty(); }
Example #30
Source File: AuthDynamicFeatureTest.java From dropwizard-simpleauth with Apache License 2.0 | 5 votes |
@Override public Optional<String> authenticate(BasicCredentials credentials) throws AuthenticationException { if (credentials.getUsername().equals("user") && credentials.getPassword().equals("password")) return Optional.of("user"); return Optional.empty(); }