io.dropwizard.auth.Authenticator Java Examples

The following examples show how to use io.dropwizard.auth.Authenticator. 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: 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 #2
Source File: AuthUtil.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: SingularityAuthFeature.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Override
public boolean configure(FeatureContext context) {
  context.register(
    new AbstractBinder() {

      @Override
      public void configure() {
        bind(SingularityMultiMethodAuthenticator.class)
          .to(
            new TypeLiteral<Authenticator<ContainerRequestContext, SingularityUser>>() {}
          )
          .in(Singleton.class);
        bind(SingularityAuthedUserFactory.class)
          .to(SingularityAuthedUserFactory.class)
          .in(Singleton.class);
        bind(SingularityAuthFactoryProvider.class)
          .to(ValueFactoryProvider.class)
          .in(Singleton.class);
        bind(SingularityAuthParamInjectionResolver.class)
          .to(new TypeLiteral<InjectionResolver<Auth>>() {})
          .in(Singleton.class);
      }
    }
  );
  return true;
}
 
Example #4
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 #5
Source File: LdapAuthenticatorFactory.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Override public Authenticator<BasicCredentials, User> build(DSLContext dslContext) {
  logger.debug("Creating LDAP authenticator");
  LdapConnectionFactory connectionFactory =
      new LdapConnectionFactory(getServer(), getPort(), getUserDN(), getPassword(),
          getTrustStorePath(), getTrustStorePassword(), getTrustStoreType());
  return new LdapAuthenticator(connectionFactory, getLookup());
}
 
Example #6
Source File: CachingJwtAuthenticator.java    From dropwizard-auth-jwt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new cached authenticator.
 *
 * @param metricRegistry the application's registry of metrics
 * @param authenticator  the underlying authenticator
 * @param builder        a {@link CacheBuilder}
 */
public CachingJwtAuthenticator(final MetricRegistry metricRegistry,
                               final Authenticator<JwtContext, P> authenticator,
                               final CacheBuilder<Object, Object> builder) {
    this.authenticator = authenticator;
    this.cacheMisses = metricRegistry.meter(name(authenticator.getClass(), "cache-misses"));
    this.gets = metricRegistry.timer(name(authenticator.getClass(), "gets"));
    this.cache = builder.recordStats().build();
}
 
Example #7
Source File: AuthResource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public AuthResource(Authenticator<ThirdEyeCredentials, ThirdEyePrincipal> authenticator,
    long cookieTTL) {
  this.authenticator = authenticator;
  this.cookieTTL = cookieTTL;
  this.sessionDAO = DAO_REGISTRY.getSessionDAO();
  this.random = new Random();
  this.random.setSeed(System.currentTimeMillis());
}
 
Example #8
Source File: ThirdEyeAuthFilter.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public ThirdEyeAuthFilter(Authenticator<ThirdEyeCredentials, ThirdEyePrincipal> authenticator, Set<String> allowedPaths, List<String> administrators, SessionManager sessionDAO) {
  this.authenticator = authenticator;
  this.allowedPaths = allowedPaths;
  this.sessionDAO = sessionDAO;
  if (administrators != null) {
    this.administrators = new HashSet<>(administrators);
  }
}
 
Example #9
Source File: TenacityAuthenticatorTest.java    From tenacity with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
    mockAuthenticator = mock(Authenticator.class);
    tenacityAuthenticator = TenacityAuthenticator.wrap(mockAuthenticator, DependencyKey.TENACITY_AUTH_TIMEOUT);
    environment.jersey().register(new AuthDynamicFeature(
            new BasicCredentialAuthFilter.Builder<>()
                    .setAuthenticator(tenacityAuthenticator)
                    .setRealm("test-realm")
                    .buildAuthFilter()));
    environment.jersey().register(tenacityExceptionMapper);
    environment.jersey().register(tenacityContainerExceptionMapper);
    environment.jersey().register(new AuthErrorResource());
}
 
Example #10
Source File: JsonWebTokenAuthFilterTest.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Test(expected = WebApplicationException.class)
public void testFilterThrowsWebApplicationExceptionIfAuthenticatorReturnsAnEmptyOptional() throws AuthenticationException, IOException {
    final Authenticator<String, Principal> authenticator = mock(Authenticator.class);
    when(authenticator.authenticate(any())).thenReturn(Optional.empty());

    final JsonWebTokenAuthFilter filter = createAuthFilterWithAuthenticator(authenticator);

    final ContainerRequestContext request = createDummyRequest();

    filter.filter(request);
}
 
Example #11
Source File: JsonWebTokenAuthFilterTest.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Test(expected = WebApplicationException.class)
public void testFilterThrowsWebApplicationExceptionIfAuthenticatorThrowsAuthenticationException() throws AuthenticationException, IOException {
    final Authenticator<String, Principal> authenticator = mock(Authenticator.class);
    when(authenticator.authenticate(any())).thenThrow(new AuthenticationException("Cannot authenticate"));

    final JsonWebTokenAuthFilter filter = createAuthFilterWithAuthenticator(authenticator);

    final ContainerRequestContext request = createDummyRequest();

    filter.filter(request);
}
 
Example #12
Source File: JsonWebTokenAuthFilterTest.java    From jobson with Apache License 2.0 5 votes vote down vote up
private static Authenticator<String, Principal> generateAlwaysAuthenticatesMock() throws AuthenticationException {
    final Authenticator<String, Principal> authenticator = mock(Authenticator.class);
    final Principal principal = generateValidUser();

    when(authenticator.authenticate(any())).thenReturn(Optional.of(principal));

    return authenticator;
}
 
Example #13
Source File: TenacityAuthenticator.java    From tenacity with Apache License 2.0 4 votes vote down vote up
public static <C, P extends Principal> Authenticator<C, P> wrap(Authenticator<C, P> authenticator,
        TenacityPropertyKey tenacityPropertyKey) {
    return new TenacityAuthenticator<>(authenticator, tenacityPropertyKey);
}
 
Example #14
Source File: BasicAuthBuilder.java    From eagle with Apache License 2.0 4 votes vote down vote up
private Authenticator<BasicCredentials, User> cache(Authenticator<BasicCredentials, User> authenticator) {
    return new CachingAuthenticator<>(environment.metrics(), authenticator, CacheBuilderSpec.parse(authConfig.getCachePolicy()));
}
 
Example #15
Source File: TenacityAuthenticator.java    From tenacity with Apache License 2.0 4 votes vote down vote up
private TenacityAuthenticator(Authenticator<C, P> underlying, TenacityPropertyKey tenacityPropertyKey) {
    this.underlying = underlying;
    this.tenacityPropertyKey = tenacityPropertyKey;
}
 
Example #16
Source File: TenacityAuthenticatorTest.java    From tenacity with Apache License 2.0 4 votes vote down vote up
public static Authenticator<BasicCredentials, Principal> getMockAuthenticator() {
    return mockAuthenticator;
}
 
Example #17
Source File: LdapHealthCheck.java    From dropwizard-auth-ldap with Apache License 2.0 4 votes vote down vote up
public LdapHealthCheck(Authenticator<BasicCredentials, T> ldapAuthenticator) {
    this.ldapAuthenticator = checkNotNull(ldapAuthenticator, "ldapAuthenticator cannot be null");
}
 
Example #18
Source File: TenacityAuthenticatorTest.java    From tenacity with Apache License 2.0 4 votes vote down vote up
public static Authenticator<BasicCredentials, Principal> getTenacityAuthenticator() {
    return tenacityAuthenticator;
}
 
Example #19
Source File: BasicAuthentication.java    From dropwizard-jaxws with Apache License 2.0 4 votes vote down vote up
public BasicAuthentication(Authenticator<BasicCredentials, ?> authenticator, String realm) {
    this.authenticator = authenticator;
    this.realm = realm;
}
 
Example #20
Source File: BasicAuthentication.java    From dropwizard-jaxws with Apache License 2.0 4 votes vote down vote up
public Authenticator<BasicCredentials, ?> getAuthenticator() {
    return this.authenticator;
}
 
Example #21
Source File: JsonWebTokenAuthFilterTest.java    From jobson with Apache License 2.0 4 votes vote down vote up
private static JsonWebTokenAuthFilter<Principal> createValidAuthFilterInstance() throws AuthenticationException {
    final Authenticator<String, Principal> authenticator = generateAlwaysAuthenticatesMock();
    final Authorizer<Principal> authorizer = generateAlwaysAuthorizedMock();

    return createAuthFilter(authenticator, authorizer);
}
 
Example #22
Source File: BasicAuthBuilder.java    From eagle with Apache License 2.0 4 votes vote down vote up
public Authenticator<BasicCredentials, User> getBasicAuthenticator() {
    return this.authenticator;
}
 
Example #23
Source File: BasicAuthBuilder.java    From eagle with Apache License 2.0 4 votes vote down vote up
public BasicAuthBuilder(AuthenticationConfig authConfig, Environment environment) {
    this.authConfig = authConfig;
    this.environment = environment;
    boolean needsCaching = authConfig.needsCaching();
    Authenticator<BasicCredentials, User> authenticator;
    String realm;
    if (authConfig.isEnabled()) {
        switch (authConfig.getMode()) {
            case "simple":
                authenticator = new SimpleBasicAuthenticator(authConfig.getSimple());
                realm = SIMPLE_MODE_REALM;
                break;
            case "ldap":
                authenticator = new LdapBasicAuthenticator(authConfig.getLdap());
                realm = LDAP_MODE_REALM;
                break;
            default:
                throw new IllegalArgumentException("Invalid auth mode " + authConfig.getMode());
        }
        if (needsCaching) {
            authenticator = cache(authenticator);
        }
        this.authenticator = authenticator;
        this.basicAuthProvider = new BasicAuthProvider<>(this.authenticator, realm);
    } else {
        this.authenticator = null;
        this.basicAuthProvider = new BasicAuthProvider<User>(null, "") {
            public Injectable<User> getInjectable(ComponentContext ic, Auth a, Parameter c) {
                return new AbstractHttpContextInjectable<User>() {
                    public User getValue(HttpContext c) {
                        User user =  new User();
                        user.setName("anonymous");
                        user.setFirstName("Anonymous User (auth: false)");
                        user.setRoles(Arrays.asList(User.Role.ALL_ROLES));
                        return user;
                    }
                };
            }
        };
    }
}
 
Example #24
Source File: BasicAuthResourceFilterFactory.java    From eagle with Apache License 2.0 4 votes vote down vote up
public BasicAuthResourceFilterFactory(Authenticator<BasicCredentials, User> authenticator) {
    this.authenticator = authenticator;
}
 
Example #25
Source File: ServiceModule.java    From keywhiz with Apache License 2.0 4 votes vote down vote up
@Provides @Singleton
@Readonly Authenticator<BasicCredentials, User> authenticator(KeywhizConfig config,
    @Readonly DSLContext jooqContext) {
  return config.getUserAuthenticatorFactory().build(jooqContext);
}
 
Example #26
Source File: SessionLoginResource.java    From keywhiz with Apache License 2.0 4 votes vote down vote up
@Inject
public SessionLoginResource(@Readonly Authenticator<BasicCredentials, User> userAuthenticator,
    AuthenticatedEncryptedCookieFactory cookieFactory) {
  this.userAuthenticator = userAuthenticator;
  this.cookieFactory = cookieFactory;
}
 
Example #27
Source File: BcryptAuthenticatorFactory.java    From keywhiz with Apache License 2.0 4 votes vote down vote up
@Override public Authenticator<BasicCredentials, User> build(DSLContext dslContext) {
  logger.debug("Creating BCrypt authenticator");
  UserDAO userDAO = new UserDAO(dslContext);
  return new BcryptAuthenticator(userDAO);
}
 
Example #28
Source File: JsonWebTokenAuthFilterTest.java    From jobson with Apache License 2.0 4 votes vote down vote up
@Test
public void testSecurityContextIsAssignedToPrincipalReturnedByAuthenticator() throws AuthenticationException, IOException {
    final String username = TestHelpers.generateRandomString();
    final Principal injectedPrincipal = new PrincipalImpl(username);

    final Authenticator<String, Principal> authenticator = mock(Authenticator.class);
    when(authenticator.authenticate(any())).thenReturn(Optional.of(injectedPrincipal));

    final JsonWebTokenAuthFilter filter = createAuthFilterWithAuthenticator(authenticator);

    final ContainerRequestContext request = createDummyRequest();

    filter.filter(request);

    final SecurityContext securityContext = request.getSecurityContext();

    final String returnedName = securityContext.getUserPrincipal().getName();

    assertThat(returnedName).isEqualTo(username);
}
 
Example #29
Source File: JsonWebTokenAuthFilterTest.java    From jobson with Apache License 2.0 4 votes vote down vote up
private static JsonWebTokenAuthFilter createAuthFilterWithAuthorizer(Authorizer<Principal> authorizer) throws AuthenticationException {
    final Authenticator<String, Principal> authenticator = generateAlwaysAuthenticatesMock();

    return createAuthFilter(authenticator, authorizer);
}
 
Example #30
Source File: JsonWebTokenAuthFilterTest.java    From jobson with Apache License 2.0 4 votes vote down vote up
private static JsonWebTokenAuthFilter createAuthFilterWithAuthenticator(Authenticator<String, Principal> authenticator) {
    final Authorizer<Principal> authorizer = generateAlwaysAuthorizedMock();

    return createAuthFilter(authenticator, authorizer);
}