io.dropwizard.auth.basic.BasicCredentials Java Examples

The following examples show how to use io.dropwizard.auth.basic.BasicCredentials. 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: ChainedAuthProviderTest.java    From dropwizard-java8 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public ChainedAuthTestResourceConfig() {
    super(true, new MetricRegistry());

    final Authorizer<Principal> authorizer = AuthUtil.getTestAuthorizer(ADMIN_USER, ADMIN_ROLE);
    final AuthFilter<BasicCredentials, Principal> basicAuthFilter = new BasicCredentialAuthFilter.Builder<>()
            .setAuthenticator(AuthUtil.getBasicAuthenticator(ImmutableList.of(ADMIN_USER, ORDINARY_USER)))
            .setAuthorizer(authorizer)
            .buildAuthFilter();

    final AuthFilter<String, Principal> oAuthFilter = new OAuthCredentialAuthFilter.Builder<>()
            .setAuthenticator(AuthUtil.getSingleUserOAuthAuthenticator(BEARER_USER, ADMIN_USER))
            .setPrefix(BEARER_PREFIX)
            .setAuthorizer(authorizer)
            .buildAuthFilter();

    register(new AuthValueFactoryProvider.Binder(Principal.class));
    register(new AuthDynamicFeature(new ChainedAuthFilter<>(buildHandlerList(basicAuthFilter, oAuthFilter))));
    register(RolesAllowedDynamicFeature.class);
    register(AuthResource.class);
}
 
Example #2
Source File: TenacityAuthenticatorTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: TenacityAuthenticatorTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLogWhenExceptionIsThrown() throws AuthenticationException {
    final DefaultExceptionLogger defaultExceptionLogger = spy(new DefaultExceptionLogger());
    HystrixPlugins.getInstance().registerCommandExecutionHook(new ExceptionLoggingCommandHook(defaultExceptionLogger));
    when(mockAuthenticator.authenticate(any(BasicCredentials.class))).thenThrow(new AuthenticationException("test"));
    doCallRealMethod().when(defaultExceptionLogger).log(any(Exception.class), any(HystrixCommand.class));

    try {
        tenacityAuthenticator.authenticate(new BasicCredentials("foo", "foo"));
    } catch (HystrixRuntimeException err) {
        assertThat(Throwables.getCausalChain(err)
                .stream()
                .filter(AuthenticationException.class::isInstance)
                .findAny())
        .isNotEmpty();
    }

    verify(mockAuthenticator, times(1)).authenticate(any(BasicCredentials.class));
    verify(defaultExceptionLogger, times(1)).log(any(Exception.class), any(HystrixCommand.class));
}
 
Example #4
Source File: TenacityAuthenticatorTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: ExampleAppTest.java    From dropwizard-auth-ldap with Apache License 2.0 6 votes vote down vote up
@Override
public void run(ExampleAppConfiguration configuration, Environment environment) throws Exception {
    final LdapConfiguration ldapConfiguration = configuration.getLdapConfiguration();

    Authenticator<BasicCredentials, User> ldapAuthenticator = new CachingAuthenticator<>(
            environment.metrics(),
            new ResourceAuthenticator(new LdapAuthenticator(ldapConfiguration)),
            ldapConfiguration.getCachePolicy());

    environment.jersey().register(new AuthDynamicFeature(
            new BasicCredentialAuthFilter.Builder<User>()
                    .setAuthenticator(ldapAuthenticator)
                    .setRealm("LDAP")
                    .buildAuthFilter()));

    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));

    environment.healthChecks().register("ldap", new LdapHealthCheck<>(
            new ResourceAuthenticator(new LdapCanAuthenticate(ldapConfiguration))));
}
 
Example #6
Source File: BcryptAuthenticator.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: LdapAuthenticator.java    From dropwizard-auth-ldap with Apache License 2.0 6 votes vote down vote up
public Optional<User> authenticateAndReturnPermittedGroups(BasicCredentials credentials) throws io.dropwizard.auth.AuthenticationException {
    final String sanitizedUsername = sanitizeEntity(credentials.getUsername());
    try {
        try (AutoclosingLdapContext context = buildContext(sanitizedUsername, credentials.getPassword())) {
            Set<String> groupMemberships = getGroupMembershipsIntersectingWithRestrictedGroups(context, sanitizedUsername);
            if (!groupMemberships.isEmpty()) {
                return Optional.of(new User(sanitizedUsername, groupMemberships));
            }
        }
    } catch (AuthenticationException ae) {
        LOG.debug("{} failed to authenticate. {}", sanitizedUsername, ae);
    } catch (IOException | NamingException err) {
        throw new io.dropwizard.auth.AuthenticationException(String.format("LDAP Authentication failure (username: %s)",
                sanitizedUsername), err);
    }
    return Optional.empty();
}
 
Example #8
Source File: BasicAuthRequestFilter.java    From eagle with Apache License 2.0 6 votes vote down vote up
public BasicAuthRequestFilter(Authenticator<BasicCredentials, User> authenticator, AbstractMethod method) {
    this.authenticator = authenticator;
    this.method = method;
    this.hasPermitAllAnnotation = method.isAnnotationPresent(PermitAll.class);
    this.hasDenyAllAnnotation = method.isAnnotationPresent(DenyAll.class);
    this.hasRolesAllowedAnnotation = method.isAnnotationPresent(RolesAllowed.class);
    this.isSecurityDefined = this.hasPermitAllAnnotation || this.hasDenyAllAnnotation || this.hasRolesAllowedAnnotation;
    for (Parameter parameter : method.getMethod().getParameters()) {
        if (isAuthRequired && isAuthDefined) {
            break;
        }
        Auth[] authAnnotations = parameter.getAnnotationsByType(Auth.class);
        this.isAuthDefined = authAnnotations.length > 0 || this.isAuthDefined;
        for (Auth auth : authAnnotations) {
            this.isAuthRequired = auth.required() || this.isAuthRequired;
        }
    }
    this.isSecurityDefined = this.isAuthDefined || this.isSecurityDefined;
    Preconditions.checkArgument(!(this.hasDenyAllAnnotation && this.hasPermitAllAnnotation), "Conflict @DenyAll and @PermitAll on method " + this.method.toString());
}
 
Example #9
Source File: BreakerboxService.java    From breakerbox with Apache License 2.0 6 votes vote down vote up
private static void setupLdapAuth(LdapConfiguration ldapConfiguration, Environment environment) {
    final LdapAuthenticator ldapAuthenticator = new LdapAuthenticator(ldapConfiguration);
    final CachingAuthenticator<BasicCredentials, User> cachingAuthenticator =
            new CachingAuthenticator<>(
                    environment.metrics(),
                    TenacityAuthenticator.wrap(
                            new ResourceAuthenticator(ldapAuthenticator), BreakerboxDependencyKey.BRKRBX_LDAP_AUTH),
                    ldapConfiguration.getCachePolicy()
            );
    environment.jersey().register(new AuthDynamicFeature(
                    new BasicCredentialAuthFilter.Builder<User>()
                            .setAuthenticator(cachingAuthenticator)
                            .setRealm("breakerbox")
                            .buildAuthFilter()));
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
}
 
Example #10
Source File: LdapAuthenticatorTest.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void ldapAuthenticatorThrowsWhenAuthFails() throws Exception {
  // Zero results on a search indicates no valid user.
  when(dnSearchResult.getEntryCount()).thenReturn(0);

  Optional<User> missingUser =
      ldapAuthenticator.authenticate(new BasicCredentials("sysadmin", "badpass"));
  assertThat(missingUser).isEmpty();
}
 
Example #11
Source File: SapBasicAuthenticator.java    From SAPNetworkMonitor with GNU General Public License v3.0 5 votes vote down vote up
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 #12
Source File: SimpleBasicAuthenticatorTest.java    From eagle with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: SimpleBasicAuthenticatorTest.java    From eagle with Apache License 2.0 5 votes vote down vote up
@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 #14
Source File: SimpleBasicAuthenticatorTest.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Test
public void testNormal() {
    try {
        BasicCredentials credentials = new BasicCredentials(TEST_USERNAME, TEST_SECRET_PHRASE);
        Optional<User> result = authenticator.authenticate(credentials);
        Assert.assertTrue("result isn't present when passed correct credentials", result.isPresent());
        User user = result.get();
        Assert.assertEquals("authenticated user is not expected", TEST_USERNAME, user.getName());
    } catch (AuthenticationException e) {
        Assert.fail("unexpected error occurs: " + e.getMessage());
    }
}
 
Example #15
Source File: SimpleBasicAuthenticator.java    From eagle with Apache License 2.0 5 votes vote down vote up
public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
    if (userAccountRepository.containsKey(credentials.getUsername())
        && EncryptorFactory.getPasswordEncryptor().checkPassword(credentials.getPassword(), userAccountRepository.get(credentials.getUsername()).getEncryptedPassword())) {
        UserAccount userAccount = userAccountRepository.get(credentials.getUsername());
        return Optional.of(new User(userAccount));
    } else {
        return Optional.absent();
    }
}
 
Example #16
Source File: AuthUtil.java    From dropwizard-java8 with Apache License 2.0 5 votes vote down vote up
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 #17
Source File: LdapAuthenticatorTest.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void ldapAuthenticatorCreatesUserOnSuccess() throws Exception {
  when(ldapConnectionFactory.getLDAPConnection(PEOPLE_DN, "validpass"))
      .thenReturn(ldapUserAuthConnection);

  User user = ldapAuthenticator.authenticate(new BasicCredentials("sysadmin", "validpass"))
      .orElseThrow(RuntimeException::new);
  assertThat(user).isEqualTo(User.named("sysadmin"));
}
 
Example #18
Source File: SpecificUsernamePwAuthenticator.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Principal> authenticate(BasicCredentials basicCredentials) throws AuthenticationException {
    if (basicCredentials.getUsername().equals(username) &&
            basicCredentials.getPassword().equals(password)) {
        return Optional.of(new PrincipalImpl(username));
    } else return Optional.empty();
}
 
Example #19
Source File: ResourceAuthenticator.java    From irontest with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<SimplePrincipal> authenticate(BasicCredentials credentials) {
    User user = userDAO.findByUsername(credentials.getUsername());
    if (user != null && user.getPassword().equals(
            PasswordUtils.hashPassword(credentials.getPassword(), user.getSalt()))) {
        SimplePrincipal principal = new SimplePrincipal(credentials.getUsername());
        principal.getRoles().addAll(user.getRoles());
        return Optional.of(principal);
    }
    return Optional.empty();
}
 
Example #20
Source File: AuthDynamicFeatureTest.java    From dropwizard-simpleauth with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #21
Source File: BasicAuthenticator.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Override
public java.util.Optional<Principal> authenticate(BasicCredentials credentials) throws AuthenticationException {
  Subject subject = SecurityUtils.getSubject();
  try {
    subject.login(new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword(), false));
    User user = new User(subject);
    return Optional.of(user);
  } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) {
    logger.log(Level.WARNING, e.getMessage(), e);
  } catch (org.apache.shiro.authc.AuthenticationException ae) {
    logger.log(Level.WARNING, ae.getMessage(), ae);
  }
  return Optional.empty();
}
 
Example #22
Source File: ChainedAuthProviderTest.java    From dropwizard-java8 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<AuthFilter> buildHandlerList(AuthFilter<BasicCredentials, Principal> basicAuthFilter,
                                         AuthFilter<String, Principal> oAuthFilter) {
    final List<AuthFilter> handlers = Lists.newArrayList();
    handlers.add(basicAuthFilter);
    handlers.add(oAuthFilter);
    return handlers;
}
 
Example #23
Source File: BasicCredentialAuthFilterTest.java    From dropwizard-simpleauth with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: ExampleAuthenticator.java    From dropwizard-java8 with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
    if ("secret".equals(credentials.getPassword())) {
        return Optional.of(new User(credentials.getUsername()));
    }
    return Optional.empty();
}
 
Example #25
Source File: ResourceAuthenticator.java    From dropwizard-auth-ldap with Apache License 2.0 5 votes vote down vote up
@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 #26
Source File: LdapAuthenticator.java    From dropwizard-auth-ldap with Apache License 2.0 5 votes vote down vote up
public boolean authenticate(BasicCredentials credentials) throws io.dropwizard.auth.AuthenticationException {
    final String sanitizedUsername = sanitizeEntity(credentials.getUsername());
    try {
        try (AutoclosingLdapContext context = buildContext(sanitizedUsername, credentials.getPassword())) {
            return filterByGroup(context, sanitizedUsername);
        }
    } catch (AuthenticationException ae) {
        LOG.debug("{} failed to authenticate. {}", sanitizedUsername, ae);
    } catch (IOException | NamingException err) {
        throw new io.dropwizard.auth.AuthenticationException(String.format("LDAP Authentication failure (username: %s)",
                sanitizedUsername), err);
    }
    return false;
}
 
Example #27
Source File: LdapHealthCheck.java    From dropwizard-auth-ldap with Apache License 2.0 5 votes vote down vote up
@Override
public Result check() throws AuthenticationException {
    if (ldapAuthenticator.authenticate(new BasicCredentials("", "")).isPresent()) {
        return Result.healthy();
    } else {
        return Result.unhealthy("Cannot contact authentication service");
    }
}
 
Example #28
Source File: LdapHealthCheckTest.java    From dropwizard-auth-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void healthy() throws Exception {
    LdapAuthenticator ldapAuthenticator = mock(LdapAuthenticator.class);
    when(ldapAuthenticator.authenticate(any(BasicCredentials.class))).thenReturn(true);
    LdapHealthCheck healthCheck = new LdapHealthCheck<>(new ResourceAuthenticator(ldapAuthenticator));
    assertThat(healthCheck.check(), is(HealthCheck.Result.healthy()));
}
 
Example #29
Source File: BasicAuthenticator.java    From dropwizard-jaxws with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<User> authenticate(BasicCredentials credentials) {
    if ("secret".equals(credentials.getPassword())) {
        return Optional.of(new User(credentials.getUsername()));
    }
    // Note that Authenticator should only throw an AuthenticationException
    // if it is unable to check the credentials.
    return Optional.empty();
}
 
Example #30
Source File: BasicAuthenticator.java    From dropwizard-jaxws with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<User> authenticate(BasicCredentials credentials) {
    if ("secret".equals(credentials.getPassword())) {
        return Optional.of(new User(credentials.getUsername()));
    }
    // Note that Authenticator should only throw an AuthenticationException
    // if it is unable to check the credentials.
    return Optional.empty();
}