@Test public void postNewTodoItem() throws UnsupportedEncodingException, AuthenticationException { final String newTodoItem = fixture("fixtures/todoItem_new.json"); final TodoItem expectedTodoItem = new TodoItem(1, "make new todo items", true); when(oaccBasicAuthenticator.authenticate(any(BasicCredentials.class))) .thenReturn(java.util.Optional.ofNullable(oaccPrincipal)); when(oaccPrincipal.getAccessControlContext()).thenReturn(oacc); when(todoItemService.createItem(eq(oacc), any(TodoItem.class))) .thenReturn(expectedTodoItem); final Response response = resources.getJerseyTest() .target("/todos") .request() .header(Header.Authorization.name(), getBasicAuthHeader(EMAIL, PASSWORD)) .post(Entity.entity(newTodoItem, MediaType.APPLICATION_JSON)); assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); // 200 OK assertThat(response.readEntity(TodoItem.class)).isEqualTo(expectedTodoItem); }
@Test public void postNewTodoItemThatFailsValidation() throws AuthenticationException, UnsupportedEncodingException { final String blankTodoItem = fixture("fixtures/todoItem_blank.json"); when(oaccBasicAuthenticator.authenticate(any(BasicCredentials.class))) .thenReturn(java.util.Optional.ofNullable(oaccPrincipal)); when(oaccPrincipal.getAccessControlContext()).thenReturn(oacc); when(todoItemService.createItem(eq(oacc), any(TodoItem.class))) .thenThrow(new IllegalArgumentException("Either title or completed (or both) is required")); final Response response = resources.getJerseyTest() .target("/todos") .request() .header(Header.Authorization.name(), getBasicAuthHeader(EMAIL, PASSWORD)) .post(Entity.entity(blankTodoItem, MediaType.APPLICATION_JSON)); assertThat(response.getStatus()).isEqualTo(422); // 422 Unprocessable Entity verifyZeroInteractions(oacc); }
@Test public void getTodoItems() throws AuthenticationException, UnsupportedEncodingException { final List<TodoItem> expectedTodoItems = Collections.singletonList(new TodoItem(1, "list all items", true)); when(oaccBasicAuthenticator.authenticate(any(BasicCredentials.class))) .thenReturn(java.util.Optional.ofNullable(oaccPrincipal)); when(oaccPrincipal.getAccessControlContext()).thenReturn(oacc); when(todoItemService.findByAuthenticatedUser(eq(oacc))) .thenReturn(expectedTodoItems); final Response response = resources.getJerseyTest() .target("/todos") .request() .header(Header.Authorization.name(), getBasicAuthHeader(EMAIL, PASSWORD)) .get(); assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); // 200 OK }
@Test public void patchTodoItem() throws AuthenticationException, UnsupportedEncodingException { final long todoItemId = 1; final String todoItem = fixture("fixtures/todoItem_new.json"); final TodoItem expectedTodoItem = new TodoItem(1, "update titles", false); when(oaccBasicAuthenticator.authenticate(any(BasicCredentials.class))) .thenReturn(java.util.Optional.ofNullable(oaccPrincipal)); when(oaccPrincipal.getAccessControlContext()).thenReturn(oacc); when(todoItemService.updateItem(eq(oacc), any(Long.class), any(TodoItem.class))) .thenReturn(expectedTodoItem); final Response response = resources.getJerseyTest() .target("/todos/" + todoItemId) .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) // to support PATCH .request() .header(Header.Authorization.name(), getBasicAuthHeader(EMAIL, PASSWORD)) .build("PATCH", Entity.entity(todoItem, MediaType.APPLICATION_JSON)) .invoke(); assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); // 200 OK assertThat(response.readEntity(TodoItem.class)).isEqualTo(expectedTodoItem); }
@Test public void patchTodoItemWithoutAuthorization() throws AuthenticationException, UnsupportedEncodingException { final long todoItemId = 1; final String todoItem = fixture("fixtures/todoItem_new.json"); when(oaccBasicAuthenticator.authenticate(any(BasicCredentials.class))) .thenReturn(java.util.Optional.ofNullable(oaccPrincipal)); when(oaccPrincipal.getAccessControlContext()).thenReturn(oacc); when(todoItemService.updateItem(eq(oacc), any(Long.class), any(TodoItem.class))) .thenThrow(new NotAuthorizedException("not authorized")); final Response response = resources.getJerseyTest() .target("/todos/" + todoItemId) .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) // to support PATCH .request() .header(Header.Authorization.name(), getBasicAuthHeader(EMAIL, PASSWORD)) .build("PATCH", Entity.entity(todoItem, MediaType.APPLICATION_JSON)) .invoke(); assertThat(response.getStatus()).isEqualTo(Response.Status.FORBIDDEN.getStatusCode()); // 403 Forbidden }
@Test public void patchTodoItemThatDoesNotExist() throws AuthenticationException, UnsupportedEncodingException { final long todoItemId = 1; final String todoItem = fixture("fixtures/todoItem_new.json"); when(oaccBasicAuthenticator.authenticate(any(BasicCredentials.class))) .thenReturn(java.util.Optional.ofNullable(oaccPrincipal)); when(oaccPrincipal.getAccessControlContext()).thenReturn(oacc); when(todoItemService.updateItem(eq(oacc), any(Long.class), any(TodoItem.class))) .thenThrow(new IllegalArgumentException("Resource " + todoItemId + " not found!")); final Response response = resources.getJerseyTest() .target("/todos/" + todoItemId) .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) // to support PATCH .request() .header(Header.Authorization.name(), getBasicAuthHeader(EMAIL, PASSWORD)) .build("PATCH", Entity.entity(todoItem, MediaType.APPLICATION_JSON)) .invoke(); assertThat(response.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode()); // 404 Not Found verifyZeroInteractions(oacc); }
@Test public void patchTodoItemThatFailsValidation() throws AuthenticationException, UnsupportedEncodingException { final long todoItemId = 1; final String blankTodoItem = fixture("fixtures/todoItem_blank.json"); when(oaccBasicAuthenticator.authenticate(any(BasicCredentials.class))) .thenReturn(java.util.Optional.ofNullable(oaccPrincipal)); when(oaccPrincipal.getAccessControlContext()).thenReturn(oacc); when(todoItemService.updateItem(eq(oacc), any(Long.class), any(TodoItem.class))) .thenThrow(new IllegalArgumentException("Either title or completed (or both) is required.")); final Response response = resources.getJerseyTest() .target("/todos/" + todoItemId) .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) // to support PATCH .request() .header(Header.Authorization.name(), getBasicAuthHeader(EMAIL, PASSWORD)) .build("PATCH", Entity.entity(blankTodoItem, MediaType.APPLICATION_JSON)) .invoke(); assertThat(response.getStatus()).isEqualTo(422); // 422 Unprocessable Entity verifyZeroInteractions(oacc); }
private Optional<String> lookup(final BasicCredentials creds) { final File file = new File(credentialsFile); if (!file.exists()) { return empty(); } try (final Stream<String> fileLines = lines(file.toPath())) { return fileLines.map(String::trim).filter(line -> !line.startsWith("#")) .map(line -> line.split(":", 3)).filter(x -> x.length == 3) .filter(d -> d[0].trim().equals(creds.getUsername()) && d[1].trim().equals(creds.getPassword())) .map(d -> d[2].trim()).findFirst(); } catch (final IOException ex) { LOGGER.error("Error processing credentials file: {}", ex.getMessage()); } return empty(); }
@Override public Optional<Person> authenticate(BasicCredentials credentials) throws AuthenticationException { List<Person> p = dao.findByDomainUsername(credentials.getUsername()); if (p.size() > 0) { Person person = p.get(0); if (person.getStatus().equals(PersonStatus.INACTIVE)) { //An Inactive person just logged in, make them active. person.setStatus(PersonStatus.ACTIVE); AnetObjectEngine.getInstance().getPersonDao().update(person); } return Optional.of(person); } if (credentials.getUsername().equals(credentials.getPassword())) { //Special development mechanism to perform a 'first login'. Person newUser = new Person(); newUser.setName(credentials.getUsername()); newUser.setRole(Role.ADVISOR); newUser.setDomainUsername(credentials.getUsername()); newUser.setStatus(PersonStatus.NEW_USER); newUser = dao.insert(newUser); return Optional.of(newUser); } return Optional.empty(); }
@Override public Optional<User> authenticate(final BasicCredentials credentials) throws AuthenticationException { String username = credentials.getUsername(); String password = credentials.getPassword(); try { try (AutoclosableDirContext context = buildContext(username, password)) { //Get the user DN SearchResult userSearched = searchUser(context, username); //Check if user is in the prod group final boolean prodUser = checkIfUserBelongsToGroup(context, userSearched.getNameInNamespace(), configuration.getProdGroupName()); final boolean techUser = checkIfUserBelongsToGroup(context, userSearched.getNameInNamespace(), configuration.getTechGroupName()); User user = new User(username, prodUser, techUser); return Optional.of(user); } } catch (NamingException e) { LOGGER.debug("{} failed to authenticate {}", username); } return Optional.empty(); }
@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']"); } }
@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(); } String password = credentials.getPassword(); // Get hashed password column from BCrypt table by username Optional<String> optionalHashedPwForUser = userDAO.getHashedPassword(username); if (!optionalHashedPwForUser.isPresent()) { return Optional.empty(); } if (BCrypt.checkpw(password, optionalHashedPwForUser.get())) { user = User.named(username); } return Optional.ofNullable(user); }
@UnitOfWork public Optional<User> authenticate(final BasicCredentials basicCredentials) throws AuthenticationException { String email = basicCredentials.getUsername(); String plaintextPassword = basicCredentials.getPassword(); final Optional<User> user = userDao.findByEmail(email); if (user.isPresent()) { final User existingUser = user.get(); checkState(existingUser.getPassword() != null, "Cannot authenticate: user with id: %s (email: %s) without password", existingUser.getId(), existingUser.getEmail()); if (isMatched(plaintextPassword, existingUser.getPassword())) { return user; } } return Optional.absent(); }
private Optional<Peer> authenticateEncrypted(BasicCredentials credentials) { Set<Peer> peers = ImmutableSet.<Peer>copyOf( Collections2.filter(allPeers, (Peer p) -> p.getName().equals(credentials.getUsername()))); if (peers.isEmpty()) { LOGGER.debug("No peer named {} found in our allowed-peers file", credentials.getUsername()); return Optional.empty(); } else { Peer peer = peers.stream().findFirst().get(); if (this.passwordEncryptor.checkPassword(credentials.getPassword(), peer.getPassword())) { LOGGER.debug("{} authenticated and allowed to request service", credentials.getUsername()); return Optional.of(peer); } else { LOGGER.debug("{} is not known in our list of allowed peers", credentials.getUsername()); return Optional.empty(); } } }
/** * <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)); }
private static void setupLdapAuth(LdapConfiguration ldapConfiguration, Environment environment) { final LdapAuthenticator ldapAuthenticator = new LdapAuthenticator(ldapConfiguration); final ResourceAuthenticator canAuthenticate = new ResourceAuthenticator( new LdapCanAuthenticate(ldapConfiguration)); final CachingAuthenticator<BasicCredentials, BasicCredentials> cachingAuthenticator = new CachingAuthenticator<>( environment.metrics(), TenacityAuthenticator.wrap( new ResourceAuthenticator(ldapAuthenticator), BreakerboxDependencyKey.BRKRBX_LDAP_AUTH), ldapConfiguration.getCachePolicy() ); environment.healthChecks().register("ldap-auth", new LdapHealthCheck<>(TenacityAuthenticator .wrap(canAuthenticate, BreakerboxDependencyKey.BRKRBX_LDAP_AUTH))); environment.jersey().register(new BasicAuthProvider<>(cachingAuthenticator, "breakerbox")); }
@Override public Optional<String> authenticate(BasicCredentials credentials) throws AuthenticationException { checkNotNull(credentials); String username = credentials.getUsername(); String secret = credentials.getPassword(); ApiKey key = provider.get(username); if (key == null) { return Optional.absent(); } if (!secret.equals(key.getSecret())) { return Optional.absent(); } return Optional.of(key.getUsername()); }
@PUT @Path("/{service}") @Consumes(MediaType.APPLICATION_JSON) public void put( @Auth BasicCredentials user, @PathParam("service") final String service, ServiceMetadata serviceMetadata) { if (service.equals(serviceMetadata.getId())) { if (serviceRegistry.updateServiceIfPresent(serviceMetadata)) { LOG.info("Service settings updated by " + user.getUsername()); } else { throw new WebApplicationException(Response.Status.NOT_FOUND); } } else { throw new WebApplicationException(Response.Status.BAD_REQUEST); } }
@GET @Path("/download/{service}/{id}/{filename}") @Produces(MediaType.TEXT_PLAIN) public DownloadView downloadBackup( @Context UriInfo context, @Auth BasicCredentials credentials, @PathParam("service") String service, @PathParam("id") String id, @PathParam("filename") String filename) throws URISyntaxException { final String temporaryToken = tokenGenerator.create(service); LOG.info("SecEvent: Created temporary token for {} to download {} backups", credentials.getUsername(), service); final URI requestURI = context.getRequestUri(); final String root = new URI(requestURI.getScheme(), null, requestURI.getHost(), requestURI.getPort(), null, null, null).toString(); return new DownloadView(root, service, id, filename, temporaryToken); }
@Override public com.google.common.base.Optional<Player> authenticate(BasicCredentials basicCredentials) throws AuthenticationException { Preconditions.checkNotNull(basicCredentials, "basicCredentials"); Optional<Player> player = playerService.findWithUsername(basicCredentials.getUsername()); if (player.isPresent()) { try { if (passwordService.verify(basicCredentials.getPassword(), player.get().getPassword())) { return com.google.common.base.Optional.of(player.get()); } } catch (PasswordException e) { throw new AuthenticationException("Exception while authenticating", e); } } return com.google.common.base.Optional.absent(); }
@Override public Optional<Player> authenticate(BasicCredentials credentials) { @Cleanup DBCursor<Player> dbPlayer = playerCollection.find( DBQuery.is("username", credentials.getUsername()), new BasicDBObject()); if (dbPlayer == null || !dbPlayer.hasNext()) { return Optional.empty(); } Player player = dbPlayer.next(); CivSingleton.instance().playerCache().put(player.getId(), player.getUsername()); if (player.getPassword().equals(DigestUtils.sha1Hex(credentials.getPassword()))) { return Optional.of(player); } return Optional.empty(); }
@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); }
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)); }
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(); }
@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(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; } }
@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)); }
@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)); }
@Override public String authenticate(HttpServletRequest request) throws AuthenticationException { BasicCredentials credentials = getCredentials(request); if (credentials == null) { throw new AuthenticationException("Could not parse Basic Authorization header", "Anonymous", request.getRemoteAddr()); } try { Optional<T> user = authenticator.authenticate(credentials); if (!user.isPresent()) { throw new AuthenticationException("User authention failed", credentials.getUsername(), request.getRemoteAddr()); } } catch (io.dropwizard.auth.AuthenticationException e) { throw new AuthenticationException("User authention failed", e, credentials.getUsername(), request.getRemoteAddr()); } return credentials.getUsername(); }
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(); }
@Override public Optional<Principal> authenticate(BasicCredentials basicCredentials) throws AuthenticationException { final UserId id = new UserId(basicCredentials.getUsername()); return readonlyUserDAO .getUserCredentialsById(id) .filter(BasicAuthenticator::hasCorrectAuthType) .filter(credentials -> matchesTheCredentialsSuppliedByTheClient(credentials, basicCredentials)) .map(UserCredentials::getId) .map(UserId::toString) .map(PrincipalImpl::new); }
@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(); }
@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()); }