@Override public boolean configure(final FeatureContext featureContext) { final UserRepository userRepo = CDI.current().select(UserRepository.class).get(); final Authenticator<String, User> authenticator = new GoogleAuthenticator( authConfig.getClientId(), userRepo, authConfig.getHostedDomain() ); final Authenticator<String, User> cachingAuthenticator = new CachingAuthenticator<>( metricRegistry, authenticator, authConfig.getAuthenticationCachePolicy() ); featureContext.register(new AuthDynamicFeature( new OAuthCredentialAuthFilter.Builder<User>() .setAuthenticator(cachingAuthenticator) .setPrefix("Bearer") .buildAuthFilter())); featureContext.register(new AuthValueFactoryProvider.Binder<>(User.class)); return true; }
@JsonIgnore public Optional<Authenticator<BasicCredentials, User>> getAuthenticator() { final String authType = authenticatorType.toLowerCase(); if (authType.equals("none")) { return Optional.empty(); } else if (authType.equals("simple")) { return Optional.of(new SimpleAuthenticator()); } else if (authType.equals("ldap")) { if (ldapConfiguration == null) { throw new IllegalArgumentException("Authenticator type is set to 'ldap' but ldap configuration is empty."); } return Optional.of(new LDAPAuthenticator(ldapConfiguration)); } else { throw new IllegalArgumentException("Authenticator " + authenticatorType + " is unknow. Use one of ['none', 'simple', 'ldap']"); } }
public JWTAuthTestResourceConfig() { super(true, new MetricRegistry()); final Authenticator<String, String> authenticator = new Authenticator<String, String>() { @Override public Optional<String> authenticate(String credentials) throws AuthenticationException { if ("good-one".equals(credentials)) { return Optional.of("good-one"); } if ("bad-one".equals(credentials)) { throw new AuthenticationException("server ran out of entropy"); } return Optional.absent(); } }; register(AuthFactory.binder(new JwtAuthFactory<>(authenticator, REALM, String.class).prefix(PREFIX))); register(AuthResource.class); }
/** * <p>If a credentialFile is provided, this method will use that file to populate the list of Peers the Authenticator * checks during request processing. If instead the "users" and "passwords" Strings are provided, this method will use * those to populate the list of Peers.</p> * @return An Authenticator appropriate for registering with Jersey as described * https://dropwizard.github.io/dropwizard/manual/auth.html */ public Authenticator<BasicCredentials, Peer> createAuthenticator() { PasswordEncryptor passwordEncryptor = encryptor.getPasswordEncryptor(); if (this.credentialFile != null) { InputStream allowedPeersResource = this.getClass().getClassLoader().getResourceAsStream(this.credentialFile); return new AllowedPeerAuthenticator(new FlatFilePeerDAO(allowedPeersResource), passwordEncryptor); } else if (this.users != null && this.passwords != null && this.delimiter != null) { return new AllowedPeerAuthenticator(new StringPeerDAO(this.users, this.passwords, this.delimiter), passwordEncryptor); } else { throw new IllegalStateException("Illegal call to createAuthenticator() when no valid configuration was set"); } }
/** * * @param environment The Dropwizard environment * @param authorizer A specific authorizer to use instead of the default PermitAllAuthorizer. See * http://www.dropwizard.io/0.9.1/docs/manual/auth.html for more details */ public void registerAuthenticator(Environment environment, Authorizer<Peer> authorizer) { Preconditions.checkNotNull(environment, "Illegal call to registerAuthenticator with a null Environment object"); Authenticator<BasicCredentials, Peer> authenticator; if (this.cachePolicy != null) { authenticator = createCachingAuthenticator(environment.metrics()); } else { authenticator = createAuthenticator(); } environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<Peer>() .setAuthenticator(authenticator) .setAuthorizer(authorizer) .setRealm(this.realm) .buildAuthFilter())); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Peer.class)); }
@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)))); }
@Test public void testAuthenticate() throws AuthenticationException { final Authenticator<BasicCredentials, Principal> authenticator = new BasicAuthenticator(getAuthFile()); final BasicCredentials credentials = new BasicCredentials("acoburn", "secret"); final Optional<Principal> res = authenticator.authenticate(credentials); assertTrue(res.isPresent()); res.ifPresent(p -> { assertEquals("https://acoburn.people.amherst.edu/", p.getName()); }); }
@Test public void testAuthenticateNoWebid() throws AuthenticationException { final Authenticator<BasicCredentials, Principal> authenticator = new BasicAuthenticator(getAuthFile()); final BasicCredentials credentials = new BasicCredentials("other", "pass"); final Optional<Principal> res = authenticator.authenticate(credentials); assertFalse(res.isPresent()); }
@Test public void testAuthenticateInvalid() throws AuthenticationException { final Authenticator<BasicCredentials, Principal> authenticator = new BasicAuthenticator(getAuthFile()); final BasicCredentials credentials = new BasicCredentials("acoburn", "incorrect"); final Optional<Principal> res = authenticator.authenticate(credentials); assertFalse(res.isPresent()); }
@Test public void testAuthenticateInvalidFile() throws AuthenticationException { final Authenticator<BasicCredentials, Principal> authenticator = new BasicAuthenticator( getAuthFile() + "missing"); final BasicCredentials credentials = new BasicCredentials("acoburn", "incorrect"); final Optional<Principal> res = authenticator.authenticate(credentials); assertFalse(res.isPresent()); }
@Test public void testAuthenticateUnreadableFile() throws AuthenticationException { final Authenticator<BasicCredentials, Principal> authenticator = new BasicAuthenticator(getAuthFile()); final BasicCredentials credentials = new BasicCredentials("acoburn", "secret"); final File userFile = new File(getAuthFile()); assumeTrue(userFile.setReadable(false)); final Optional<Principal> res = authenticator.authenticate(credentials); assertFalse(res.isPresent()); userFile.setReadable(true); }
@Test public void testAuthenticate() throws AuthenticationException { final Authenticator<String, Principal> authenticator = new AnonymousAuthenticator(); final Optional<Principal> res = authenticator.authenticate("blahblah"); assertTrue(res.isPresent()); res.ifPresent(p -> { assertEquals(Trellis.AnonymousAgent.getIRIString(), p.getName()); }); }
@Test public void testAuthenticate() throws AuthenticationException { final String key = "c2VjcmV0"; final String token = Jwts.builder().setSubject("https://acoburn.people.amherst.edu") .signWith(SignatureAlgorithm.HS512, key).compact(); final Authenticator<String, Principal> authenticator = new JwtAuthenticator(key, true); final Optional<Principal> result = authenticator.authenticate(token); assertTrue(result.isPresent()); result.ifPresent(p -> { assertEquals("https://acoburn.people.amherst.edu", p.getName()); }); }
@Test public void testAuthenticateNoSub() throws AuthenticationException { final String key = "c2VjcmV0"; final String token = Jwts.builder().setIssuer("http://localhost") .signWith(SignatureAlgorithm.HS512, key).compact(); final Authenticator<String, Principal> authenticator = new JwtAuthenticator(key, true); final Optional<Principal> result = authenticator.authenticate(token); assertFalse(result.isPresent()); }
@Test public void testAuthenticateSubIss() throws AuthenticationException { final String key = "c2VjcmV0"; final String token = Jwts.builder().setSubject("acoburn").setIssuer("http://localhost") .signWith(SignatureAlgorithm.HS512, key).compact(); final Authenticator<String, Principal> authenticator = new JwtAuthenticator(key, true); final Optional<Principal> result = authenticator.authenticate(token); assertTrue(result.isPresent()); result.ifPresent(p -> { assertEquals("http://localhost/acoburn", p.getName()); }); }
@Test public void testAuthenticateSubNoWebIss() throws AuthenticationException { final String key = "c2VjcmV0"; final String token = Jwts.builder().setSubject("acoburn").setIssuer("some org") .signWith(SignatureAlgorithm.HS512, key).compact(); final Authenticator<String, Principal> authenticator = new JwtAuthenticator(key, true); final Optional<Principal> result = authenticator.authenticate(token); assertFalse(result.isPresent()); }
@Test public void testAuthenticateToken() throws AuthenticationException { final String key = "secret"; final String token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJodHRwczovL2Fjb2J1cm4ucGVvcGxlLmFtaGVyc3QuZWR1In0." + "ct-fzDrpgxqQVjqclpYgCoqZgysjGZFqM0nEjERwIgboC0SGq43cemyZILdeaJpp0tGPE2kHUzAWPDcZsQWPkw"; final Authenticator<String, Principal> authenticator = new JwtAuthenticator(key, false); final Optional<Principal> result = authenticator.authenticate(token); assertTrue(result.isPresent()); result.ifPresent(p -> { assertEquals("https://acoburn.people.amherst.edu", p.getName()); }); }
@Test public void testAuthenticateTokenIssSub() throws AuthenticationException { final String key = "secret"; final String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhY29idXJuIiwibmFtZSI6IkFhcm9" + "uIENvYnVybiIsImlzcyI6Imh0dHA6Ly9leGFtcGxlLm9yZy8ifQ.DPb_i9vfI5um2X_g_df2y1uFktThGdDBo-Q7AMqjaWc"; final Authenticator<String, Principal> authenticator = new JwtAuthenticator(key, false); final Optional<Principal> result = authenticator.authenticate(token); assertTrue(result.isPresent()); result.ifPresent(p -> { assertEquals("http://example.org/acoburn", p.getName()); }); }
@Test public void testAuthenticationTokenWebid() throws AuthenticationException { final String key = "secret"; final String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3ZWJpZCI6Imh0dHBzOi8vYWNvYnVybi5wZW9w" + "bGUuYW1oZXJzdC5lZHUvIiwic3ViIjoiYWNvYnVybiIsIm5hbWUiOiJBYXJvbiBDb2J1cm4iLCJpc3MiOiJodHRwOi8vZX" + "hhbXBsZS5vcmcvIn0.X-7_VfEuLGzH5ZEqzpkHWp1bo3tMzBiyDcNUwwdLeqw"; final Authenticator<String, Principal> authenticator = new JwtAuthenticator(key, false); final Optional<Principal> result = authenticator.authenticate(token); assertTrue(result.isPresent()); result.ifPresent(p -> { assertEquals("https://acoburn.people.amherst.edu/", p.getName()); }); }
@Test public void testAuthenticationTokenWebidBadKey() throws AuthenticationException { final String key = "incorrect"; final String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ3ZWJpZCI6Imh0dHBzOi8vYWNvYnVybi5wZW9w" + "bGUuYW1oZXJzdC5lZHUvIiwic3ViIjoiYWNvYnVybiIsIm5hbWUiOiJBYXJvbiBDb2J1cm4iLCJpc3MiOiJodHRwOi8vZX" + "hhbXBsZS5vcmcvIn0.X-7_VfEuLGzH5ZEqzpkHWp1bo3tMzBiyDcNUwwdLeqw"; final Authenticator<String, Principal> authenticator = new JwtAuthenticator(key, false); final Optional<Principal> result = authenticator.authenticate(token); assertFalse(result.isPresent()); }
@Test public void testAuthenticationNoPrincipal() throws AuthenticationException { final String key = "secret"; final String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhY29idXJuIiwibmFtZSI" + "6IkFhcm9uIENvYnVybiJ9.IMuzkEyDDHaLi8wps_W3F6wJkIVwocK4DFb8OFYaADA"; final Authenticator<String, Principal> authenticator = new JwtAuthenticator(key, false); final Optional<Principal> result = authenticator.authenticate(token); assertFalse(result.isPresent()); }
@Test public void testGarbledToken() throws AuthenticationException { final String key = "secret"; final String token = "blahblah"; final Authenticator<String, Principal> authenticator = new JwtAuthenticator(key, false); final Optional<Principal> result = authenticator.authenticate(token); assertFalse(result.isPresent()); }
/** * Creates a new cached authenticator. * * @param metricRegistry the application's registry of metrics * @param authenticator the underlying authenticator * @param builder a {@link CacheBuilder} */ public CorrectedCachingAuthenticator(MetricRegistry metricRegistry, Authenticator<C, Principal> authenticator, CacheBuilder<Object, Object> builder) { this.underlying = authenticator; this.cacheMisses = metricRegistry.meter(name(authenticator.getClass(), "cache-misses")); this.gets = metricRegistry.timer(name(authenticator.getClass(), "gets")); this.cache = builder.recordStats().build(); }
/** * Creates a BasicauthProvider that can user a UserContextHolder to retrieve user infos somewhere else in the code * * @param authenticator * @param realm * @param userContext */ public BasicAuthProviderWithUserContextHolder(Authenticator<BasicCredentials, User> authenticator, String realm, UserContext userContext, boolean useDefaultUserWhenAuthentFails) { // super(authenticator, realm); this.authenticator = authenticator; this.realm = realm; this.userContext = userContext; this.useDefaultUserIfAuthentFails = useDefaultUserWhenAuthentFails; }
@Test public void testCreateAuthenticatorWithCredentialFile() throws AuthenticationException { AllowedPeerConfiguration config = new AllowedPeerConfiguration(); config.setCredentialFile("peers/test-peers.properties"); Authenticator<BasicCredentials, Peer> authenticator = config.createAuthenticator(); assertTrue(authenticator.authenticate(new BasicCredentials("foo", "bar")).isPresent()); assertFalse(authenticator.authenticate(new BasicCredentials("not in", "our test properties")).isPresent()); }
@Test public void testCreateAuthenticatorWithBasicEncryptedCredentialFile() throws AuthenticationException { AllowedPeerConfiguration config = new AllowedPeerConfiguration(); config.setCredentialFile("peers/test-peers-encrypted-basic.properties"); config.setEncryptor(AllowedPeerConfiguration.Encryptor.BASIC); Authenticator<BasicCredentials, Peer> authenticator = config.createAuthenticator(); assertTrue(authenticator.authenticate(new BasicCredentials("foo", "bar")).isPresent()); assertFalse(authenticator.authenticate(new BasicCredentials("not in", "our test properties")).isPresent()); assertFalse(authenticator.authenticate(new BasicCredentials("foo", "wrong password")).isPresent()); }
@Test public void testCreateAuthenticatorWithStrings() throws AuthenticationException { AllowedPeerConfiguration config = new AllowedPeerConfiguration(); config.setUsers("bob;alice"); config.setPasswords("secret;1234"); Authenticator<BasicCredentials, Peer> authenticator = config.createAuthenticator(); assertTrue(authenticator.authenticate(new BasicCredentials("bob", "secret")).isPresent()); assertTrue(authenticator.authenticate(new BasicCredentials("alice", "1234")).isPresent()); assertFalse(authenticator.authenticate(new BasicCredentials("not in", "our strings")).isPresent()); }
private BasicAuthFactory<String> createBasicAuthFactory(AuthConfiguration config, MetricRegistry metrics) { Authenticator<BasicCredentials, String> authenticator = createAuthenticator(config); Optional<String> cacheSpec = config.getCacheSpec(); if (cacheSpec.isPresent()) { CacheBuilderSpec spec = CacheBuilderSpec.parse(cacheSpec.get()); authenticator = new CachingAuthenticator<>(metrics, authenticator, spec); } return new BasicAuthFactory<>(authenticator, config.getRealm(), String.class); }
@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; }
@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()); }
@Override public void run(ExampleConfiguration configuration, Environment environment) throws Exception { Authenticator<BasicCredentials, User> authenticator = new ExampleAuthenticator(); WebSocketInitializer<ExampleConfiguration> webSocketInitializer = new WebSocketInitializer.Builder<ExampleConfiguration>(configuration, environment) .basicAuthenticator(authenticator).build(); environment.jersey().register(new PingResource()); webSocketInitializer.onRun(); webSocketInitializer.addWebocket(new ChatServer()); environment.servlets().setSessionHandler(new SessionHandler()); environment.jersey().register(new BasicAuthProvider<User>(authenticator, "My Realm")); }
@Override protected void configure() { bind(AuthConfiguration.class).toInstance(authConfiguration); bind(ApiKeyCredentials.class).asEagerSingleton(); bind(new TypeLiteral<Authenticator<String, AuthPrincipal>>() { }) .annotatedWith(Names.named("oauthAppAuthenticator")) .to(TokenOAuthAuthenticator.class); bind(new TypeLiteral<Authorizer<AuthPrincipal>>() { }) .annotatedWith(Names.named("oauthAppAuthorizer")) .to(TokenAuthorizer.class); bind(new TypeLiteral<Authenticator<BasicCredentials, AuthPrincipal>>() { }) .annotatedWith(Names.named("basicAppAuthenticator")) .to(BasicAuthenticator.class); List<String> multipleGroupAccessList = Lists.newArrayList(); multipleGroupAccessList.addAll( Splitter.on(",").splitToList(authConfiguration.multipleGroupAccessList)); bind(new TypeLiteral<List<String>>() { }).annotatedWith(Names.named("multipleGroupAccessList")).toInstance(multipleGroupAccessList); bind(AccessControlSupport.class).asEagerSingleton(); bind(UnauthorizedHandler.class).to(DefaultUnauthorizedHandler.class); OkHttpClient.Builder builder = new OkHttpClient.Builder() .connectTimeout(authConfiguration.remoteOAuthServer.connectTimeout, TimeUnit.MILLISECONDS) .readTimeout(authConfiguration.remoteOAuthServer.connectTimeout, TimeUnit.MILLISECONDS); OkHttpClient client = builder.build(); bind(OkHttpClient.class) .annotatedWith(Names.named("OAuthServiceClient")) .toInstance(client); logger.info("op=configure_oauth,remote_oauth_lookup_url={}", authConfiguration.remoteOAuthServer.tokenLookupURI); bind(URI.class) .annotatedWith(Names.named("OAuthServiceTokenLookupUri")) .toInstance(authConfiguration.remoteOAuthServer.tokenLookupURI); }
private BasicAuthInjectable(Authenticator<BasicCredentials, T> authenticator, boolean required) { this.authenticator = authenticator; this.required = required; }
public NullAuthProvider(Authenticator<BasicCredentials, T> authenticator) { this.authenticator = authenticator; }
private Authenticator<BasicCredentials, String> createAuthenticator(AuthConfiguration config) { Map<String, ApiKey> keys = config.getApiKeys(); return new BasicCredentialsAuthenticator(keys::get); }
public TokenAuthProvider(Authenticator<TokenCredentials, T> authenticator) { this.authenticator = authenticator; }
public TokenAuthInjectable(Authenticator<TokenCredentials, T> authenticator, boolean required) { this.authenticator = authenticator; this.required = required; }
public PlayerAuthenticationCacheImpl(MetricRegistry metricRegistry, Authenticator<BasicCredentials, Player> authenticator, CacheBuilderSpec cacheSpec) { super(metricRegistry, authenticator, cacheSpec); }
@Override public Authenticator<BasicCredentials, Player> getAuthenticator() { return this; }
public AuthResource(Authenticator<Credentials, ThirdEyePrincipal> authenticator, AuthCookieSerializer serializer, long cookieTTL) { this.authenticator = authenticator; this.serializer = serializer; this.cookieTTL = cookieTTL; }