io.dropwizard.auth.AuthDynamicFeature Java Examples

The following examples show how to use io.dropwizard.auth.AuthDynamicFeature. 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: JwtAuthApplication.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
@Override
public void run(MyConfiguration configuration, Environment environment) throws Exception {
    final byte[] key = configuration.getJwtTokenSecret();

    final JwtConsumer consumer = new JwtConsumerBuilder()
        .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
        .setRequireExpirationTime() // the JWT must have an expiration time
        .setRequireSubject() // the JWT must have a subject claim
        .setVerificationKey(new HmacKey(key)) // verify the signature with the public key
        .setRelaxVerificationKeyValidation() // relaxes key length requirement
        .build(); // create the JwtConsumer instance

    environment.jersey().register(new AuthDynamicFeature(
        new JwtAuthFilter.Builder<MyUser>()
            .setJwtConsumer(consumer)
            .setRealm("realm")
            .setPrefix("Bearer")
            .setAuthenticator(new ExampleAuthenticator())
            .buildAuthFilter()));

    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Principal.class));
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    environment.jersey().register(new SecuredResource(configuration.getJwtTokenSecret()));
}
 
Example #2
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 #3
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 #4
Source File: RateLimitApplication.java    From ratelimitj with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Configuration configuration, Environment environment) {

    environment.jersey().register(new LoginResource());
    environment.jersey().register(new UserResource());
    environment.jersey().register(new TrekResource());

    environment.jersey().register(new AuthDynamicFeature(
            new OAuthCredentialAuthFilter.Builder<PrincipalImpl>()
                    .setAuthenticator(new TestOAuthAuthenticator()).setPrefix("Bearer")
                    .buildAuthFilter()));
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(PrincipalImpl.class));
}
 
Example #5
Source File: ServerApplication.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private static void enableAuthentication(
    final Environment environment, final MetricRegistry metrics, final Jdbi jdbi) {
  environment
      .jersey()
      .register(
          new AuthDynamicFeature(
              new OAuthCredentialAuthFilter.Builder<AuthenticatedUser>()
                  .setAuthenticator(buildAuthenticator(metrics, jdbi))
                  .setAuthorizer(new RoleAuthorizer())
                  .setPrefix(AuthenticationHeaders.KEY_BEARER_PREFIX)
                  .buildAuthFilter()));
  environment.jersey().register(new AuthValueFactoryProvider.Binder<>(AuthenticatedUser.class));
}
 
Example #6
Source File: KeycloakBundle.java    From keycloak-dropwizard-integration with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("checkstyle:emptyblock")
public void run(T configuration, Environment environment) {

    /* setup the authenticator in front of the requests to allow for pre-auth integration */
    // tag::authenticator[]
    KeycloakJettyAuthenticator keycloak = new KeycloakDropwizardAuthenticator();
    keycloak.setAdapterConfig(getKeycloakConfiguration(configuration));
    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    environment.getApplicationContext().setSecurityHandler(securityHandler);
    environment.getApplicationContext().getSecurityHandler().setAuthenticator(keycloak);
    // end::authenticator[]

    // tag::authfactory[]
    environment.jersey().register(new AuthDynamicFeature(
            createAuthFactory(configuration)));
    // To use @RolesAllowed annotations
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    // To use @Auth to inject a custom Principal type into your resource
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(getUserClass()));
    // end::authfactory[]

    if (getKeycloakConfiguration(configuration).isBearerOnly()) {
        // no session needed
    } else if (getKeycloakConfiguration(configuration).getTokenStore() != null
            && getKeycloakConfiguration(configuration).getTokenStore().toLowerCase(Locale.ENGLISH)
            .equals(TokenStore.COOKIE.toString().toLowerCase(Locale.ENGLISH))) {
        // no session needed
    } else {
        // allow (stateful) sessions in Dropwizard
        environment.jersey().register(HttpSessionFactory.class);
        environment.servlets().setSessionHandler(new SessionHandler());
    }
}
 
Example #7
Source File: AuthBaseResourceConfig.java    From dropwizard-auth-jwt with Apache License 2.0 5 votes vote down vote up
public AuthBaseResourceConfig() {
    super(true, new MetricRegistry());

    register(new AuthDynamicFeature(getAuthFilter()));
    register(new AuthValueFactoryProvider.Binder<>(Principal.class));
    register(RolesAllowedDynamicFeature.class);
    register(AuthResource.class);
}
 
Example #8
Source File: BreakerboxService.java    From breakerbox with Apache License 2.0 5 votes vote down vote up
private static void setupNullAuth(Environment environment) {
    environment.jersey().register(new AuthDynamicFeature(
                    new NullAuthFilter.Builder<User>()
                    .setAuthenticator(new NullAuthenticator())
                    .setRealm("null")
                    .buildAuthFilter()));
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
}
 
Example #9
Source File: OAuth2Bundle.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
@Override
public void run(Object configuration, Environment environment) throws Exception {
    environment.jersey().register(OAuth2AccessTokenResource.class);
    environment.jersey().register(OAuth2AuthorizationRequestFactory.getBinder());

    environment.jersey().register(RolesAllowedDynamicFeature.class);
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
    environment.jersey().register(new AuthDynamicFeature(
        new OAuthCredentialAuthFilter.Builder<User>()
            .setAuthenticator(new UserAuthenticator(ebeanBundle.getEbeanServer()))
            .setAuthorizer(new UserAuthorizer())
            .setPrefix("Bearer")
            .buildAuthFilter()));
}
 
Example #10
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 #11
Source File: RufusApplication.java    From rufus with MIT License 4 votes vote down vote up
@Override
public void run(RufusConfiguration conf, Environment env) throws Exception {
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(env, conf.getDataSourceFactory(), DB_SOURCE);

    final UserDao userDao = jdbi.onDemand(UserDao.class);
    final ArticleDao articleDao = jdbi.onDemand(ArticleDao.class);

    final FeedProcessorImpl processor = FeedProcessorImpl.newInstance(articleDao);
    final FeedParser parser = new FeedParser(articleDao, processor);

    final JwtConsumer jwtConsumer = new JwtConsumerBuilder()
        .setAllowedClockSkewInSeconds(30)
        .setRequireExpirationTime()
        .setRequireSubject()
        .setVerificationKey(new HmacKey(VERIFICATION_KEY))
        .setRelaxVerificationKeyValidation()
        .build();
    final CachingJwtAuthenticator<User> cachingJwtAuthenticator = new CachingJwtAuthenticator<>(
        env.metrics(),
        new JwtAuthenticator(userDao),
        conf.getAuthenticationCachePolicy()
    );

    env.jersey().register(new ArticleResource(userDao, articleDao, processor, parser));
    env.jersey().register(
        new UserResource(
            new BasicAuthenticator(userDao),
            new TokenGenerator(VERIFICATION_KEY),
            userDao,
            articleDao
        )
    );

    //route source
    env.jersey().setUrlPattern(ROOT_PATH);

    env.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
    env.jersey().register(new AuthDynamicFeature(
        new JwtAuthFilter.Builder<User>()
            .setJwtConsumer(jwtConsumer)
            .setRealm(REALM)
            .setPrefix(BEARER)
            .setAuthenticator(cachingJwtAuthenticator)
            .buildAuthFilter()
    ));
}
 
Example #12
Source File: PublicApi.java    From pay-publicapi with MIT License 4 votes vote down vote up
@Override
public void run(PublicApiConfig configuration, Environment environment) {
    initialiseSSLSocketFactory();

    final Injector injector = Guice.createInjector(new PublicApiModule(configuration, environment));

    environment.healthChecks().register("ping", new Ping());

    environment.jersey().register(injector.getInstance(HealthCheckResource.class));
    environment.jersey().register(injector.getInstance(PaymentsResource.class));
    environment.jersey().register(injector.getInstance(DirectDebitEventsResource.class));
    environment.jersey().register(injector.getInstance(PaymentRefundsResource.class));
    environment.jersey().register(injector.getInstance(RequestDeniedResource.class));
    environment.jersey().register(injector.getInstance(MandatesResource.class));
    environment.jersey().register(injector.getInstance(SearchRefundsResource.class));
    environment.jersey().register(injector.getInstance(DirectDebitPaymentsResource.class));
    environment.jersey().register(injector.getInstance(TransactionsResource.class));
    environment.jersey().register(injector.getInstance(TelephonePaymentNotificationResource.class));
    environment.jersey().register(new InjectingValidationFeature(injector));
    environment.jersey().register(injector.getInstance(ReturnUrlValidator.class));

    environment.jersey().register(injector.getInstance(RateLimiterFilter.class));
    environment.jersey().register(injector.getInstance(LoggingMDCRequestFilter.class));

    environment.servlets().addFilter("ClearMdcValuesFilter", injector.getInstance(ClearMdcValuesFilter.class))
            .addMappingForUrlPatterns(of(REQUEST), true, "/v1/*");

    environment.servlets().addFilter("AuthorizationValidationFilter", injector.getInstance(AuthorizationValidationFilter.class))
            .addMappingForUrlPatterns(of(REQUEST), true, "/v1/*");

    environment.servlets().addFilter("LoggingFilter", injector.getInstance(LoggingFilter.class))
            .addMappingForUrlPatterns(of(REQUEST), true, "/v1/*");

    /*
       Turn off 'FilteringJacksonJaxbJsonProvider' which overrides dropwizard JacksonMessageBodyProvider.
       Fails on Integration tests if not disabled. 
           - https://github.com/dropwizard/dropwizard/issues/1341
    */
    environment.jersey().property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, Boolean.TRUE);

    CachingAuthenticator<String, Account> cachingAuthenticator = new CachingAuthenticator<>(
            environment.metrics(),
            injector.getInstance(AccountAuthenticator.class),
            configuration.getAuthenticationCachePolicy());

    environment.jersey().register(new AuthDynamicFeature(
            new OAuthCredentialAuthFilter.Builder<Account>()
                    .setAuthenticator(cachingAuthenticator)
                    .setPrefix("Bearer")
                    .buildAuthFilter()));
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Account.class));

    attachExceptionMappersTo(environment.jersey());

    initialiseMetrics(configuration, environment);

    //health check removed as redis is not a mandatory dependency
    environment.healthChecks().unregister("redis");
}
 
Example #13
Source File: MqttHttp.java    From mithqtt with Apache License 2.0 4 votes vote down vote up
@Override
public void run(MqttHttpConfiguration configuration, Environment environment) throws Exception {
    // validator
    logger.debug("Initializing validator ...");
    Validator validator = new Validator(configuration);

    // storage
    SyncStorage storage = (SyncStorage) Class.forName(storageConfig.getString("storage.sync.class")).newInstance();
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
            logger.debug("Initializing storage storage ...");
            storage.init(storageConfig);
        }

        @Override
        public void stop() throws Exception {
            logger.debug("Destroying storage storage ...");
            storage.destroy();
        }
    });

    // authenticator
    Authenticator authenticator = (Authenticator) Class.forName(authenticatorConfig.getString("authenticator.class")).newInstance();
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
            logger.debug("Initializing authenticator ...");
            authenticator.init(authenticatorConfig);
        }

        @Override
        public void stop() throws Exception {
            logger.debug("Destroying authenticator ...");
            authenticator.destroy();
        }
    });

    // cluster
    Cluster cluster = (Cluster) Class.forName(clusterConfig.getString("cluster.class")).newInstance();
    environment.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
            logger.debug("Initializing cluster ...");
            cluster.init(clusterConfig, null);
        }

        @Override
        public void stop() throws Exception {
            logger.debug("Destroying cluster ...");
            cluster.destroy();
        }
    });

    // OAuth
    environment.jersey().register(new AuthDynamicFeature(
            new OAuthCredentialAuthFilter.Builder<UserPrincipal>()
                    .setAuthenticator(new OAuthAuthenticator(authenticator))
                    .setAuthorizer(new PermitAllAuthorizer<>())
                    .setPrefix("Bearer")
                    .buildAuthFilter()));
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(UserPrincipal.class));

    // register resources
    environment.jersey().register(new MqttPublishResource(configuration.getServerId(), validator, storage, cluster, authenticator));
    environment.jersey().register(new MqttSubscribeResource(configuration.getServerId(), validator, storage, cluster, authenticator));
    environment.jersey().register(new MqttUnsubscribeResource(configuration.getServerId(), validator, storage, cluster, authenticator));

    // config jackson
    environment.getObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    environment.getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    environment.getObjectMapper().configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
}