Java 类io.dropwizard.auth.AuthenticationException 实例源码

项目:outland    文件:GroupResource.java   
@GET
@Path("/{group}")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
@Timed(name = "getByKey")
public Response getByKey(
    @Auth AuthPrincipal authPrincipal,
    @PathParam("group") String group
) throws AuthenticationException {

  final long start = System.currentTimeMillis();
  final Optional<Group> maybe = findGroup(group);

  if (maybe.isPresent()) {
    accessControlSupport.throwUnlessGrantedFor(authPrincipal, maybe.get());
    return headers.enrich(Response.ok(maybe.get()), start).build();
  }

  return headers.enrich(Response.status(404).entity(
      Problem.clientProblem(GroupResource.TITLE_NOT_FOUND, "", 404)), start).build();
}
项目:outland    文件:GroupResource.java   
@DELETE
@Path("/{group}/access/services/{service_key}")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
@Timed(name = "removeService")
public Response removeService(
    @Auth AuthPrincipal authPrincipal,
    @PathParam("group") String groupKey,
    @PathParam("service_key") String serviceKey
) throws AuthenticationException {
  final long start = System.currentTimeMillis();

  final Optional<Group> maybe = findGroup(groupKey);

  if (maybe.isPresent()) {
    final Group group = maybe.get();
    accessControlSupport.throwUnlessGrantedFor(authPrincipal, group);
    final Group updated = groupService.removeServiceAccess(group, serviceKey);

    return headers.enrich(Response.ok(updated), start).build();
  }

  return headers.enrich(Response.status(404).entity(
      Problem.clientProblem(TITLE_NOT_FOUND, "", 404)), start).build();
}
项目:outland    文件:GroupResource.java   
@DELETE
@Path("/{group}/access/members/{member_key}")
@Produces(MediaType.APPLICATION_JSON)
@PermitAll
@Timed(name = "removeMember")
public Response removeMember(
    @Auth AuthPrincipal authPrincipal,
    @PathParam("group") String groupKey,
    @PathParam("member_key") String memberKey
) throws AuthenticationException {
  final long start = System.currentTimeMillis();

  final Optional<Group> maybe = findGroup(groupKey);

  if (maybe.isPresent()) {
    final Group group = maybe.get();
    accessControlSupport.throwUnlessGrantedFor(authPrincipal, group);
    final Group updated = groupService.removeMemberAccess(group, memberKey);

    return headers.enrich(Response.ok(updated), start).build();
  }

  return headers.enrich(Response.status(404).entity(
      Problem.clientProblem(TITLE_NOT_FOUND, "", 404)), start).build();
}
项目:outland    文件:GroupResource.java   
private Response postUpdate(
    AuthPrincipal authPrincipal,
    String groupKey,
    Function<Group, Group> updater
) throws AuthenticationException {

  final long start = System.currentTimeMillis();
  final Optional<Group> maybe = findGroup(groupKey);

  if (maybe.isPresent()) {
    final Group group = maybe.get();
    accessControlSupport.throwUnlessGrantedFor(authPrincipal, group);
    final Group updated = updater.apply(group);
    return headers.enrich(Response.ok(updated), start).build();
  }

  return headers.enrich(Response.status(404).entity(
      Problem.clientProblem(TITLE_NOT_FOUND, "", 404)), start).build();
}
项目:outland    文件:FeatureResource.java   
@POST
@Path("/{group}/{feature_key}")
@PermitAll
@Timed(name = "updateFeature")
public Response updateFeature(
    @Auth AuthPrincipal principal,
    @PathParam("group") String group,
    @PathParam("feature_key") String featureKey,
    Feature feature,
    @Context HttpHeaders httpHeaders
) throws AuthenticationException {

  final long start = System.currentTimeMillis();

  grantedGuard(principal, group);
  groupValidGuard(group, featureKey, feature);

  final Optional<String> maybeSeen = idempotencyChecker.extractKey(httpHeaders);
  if (maybeSeen.isPresent() && idempotencyChecker.seen(maybeSeen.get())) {
    return alreadyUpdated(feature, start, maybeSeen);
  }

  return headers.enrich(Response.ok(update(group, feature)), start).build();
}
项目:outland    文件:FeatureResource.java   
@GET
@Path("/{group}/{feature_key}")
@PermitAll
@Timed(name = "getFeatureByKey")
public Response getFeatureByKey(
    @Auth AuthPrincipal principal,
    @PathParam("group") String group,
    @PathParam("feature_key") String featureKey
) throws AuthenticationException {

  final long start = System.currentTimeMillis();
  grantedGuard(principal, group);
  return headers.enrich(
      featureService.loadFeatureByKey(group, featureKey)
          .map(Response::ok)
          .orElseGet(this::featureNotFound), start).build();
}
项目:outland    文件:AccessControlSupport.java   
public void throwUnlessGrantedFor(AuthPrincipal authPrincipal, Group group)
    throws AuthenticationException {

  if (multipleGroupAccessList.contains(authPrincipal.identifier())) {
    logger.info(kvp("op", "member_access_check",
        "multiple_group_access_granted", authPrincipal.identifier()));
    return;
  }

  if (!GroupService.MEMBER.equals(authPrincipal.type()) && !GroupService.SERVICE.equals(
      authPrincipal.type())) {
    throw new AuthenticationException("Unknown type " + authPrincipal.type());
  }

  if (GroupService.MEMBER.equals(authPrincipal.type()) && !memberHasGrant(authPrincipal, group)) {
    throw new AuthenticationException("Member not authenticated");
  }

  if (GroupService.SERVICE.equals(authPrincipal.type()) && !serviceHasGrant(authPrincipal,
      group)) {
    throw new AuthenticationException("Service not authenticated");
  }
}
项目:outland    文件:AccessControlSupport.java   
public void throwUnlessGrantedFor(AuthPrincipal authPrincipal, String group)
    throws AuthenticationException {

  if (multipleGroupAccessList.contains(authPrincipal.identifier())) {
    logger.info(kvp("op", "member_access_check",
        "multiple_group_access_granted", authPrincipal.identifier()));
    return;
  }

  if (!GroupService.MEMBER.equals(authPrincipal.type()) && !GroupService.SERVICE.equals(
      authPrincipal.type())) {
    throw new AuthenticationException("Unknown access type " + authPrincipal.type());
  }

  if (GroupService.MEMBER.equals(authPrincipal.type()) && !memberHasGrant(authPrincipal, group)) {
    throw new AuthenticationException("Member not authenticated");
  }

  if (GroupService.SERVICE.equals(authPrincipal.type()) && !serviceHasGrant(authPrincipal,
      group)) {
    throw new AuthenticationException("Service not authenticated");
  }
}
项目:oacc-example-securetodo    文件:TodoItemResourceTest.java   
@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);
}
项目:oacc-example-securetodo    文件:TodoItemResourceTest.java   
@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);
}
项目:oacc-example-securetodo    文件:TodoItemResourceTest.java   
@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
}
项目:oacc-example-securetodo    文件:TodoItemResourceTest.java   
@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);
}
项目:oacc-example-securetodo    文件:TodoItemResourceTest.java   
@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
}
项目:oacc-example-securetodo    文件:TodoItemResourceTest.java   
@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);
}
项目:oacc-example-securetodo    文件:TodoItemResourceTest.java   
@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);
}
项目:SECP    文件:SECPAuthenticator.java   
@Override
@UnitOfWork
public Optional<User> authenticate(String token) throws AuthenticationException {
    String username;

    try {
        username = tokenController.getUsernameFromToken(token);
    } catch (InvalidJwtException e) {
        throw new AuthenticationException(e);
    }

    if (StringUtils.isBlank(username)) {
        LOG.error("Username is blank.");
        return Optional.empty();
    } else {
        User user = userDAO.findByUserName(username);
        return Optional.ofNullable(user);
    }
}
项目:anet    文件:AnetDevAuthenticator.java   
@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();
}
项目:hesperides    文件:CorrectedCachingAuthenticator.java   
@Override
public Optional<Principal> authenticate(C credentials) throws AuthenticationException {
    final Timer.Context context = gets.time();
    try {
        Optional<Principal> optionalPrincipal = cache.getIfPresent(credentials);
        if (optionalPrincipal == null) {
            cacheMisses.mark();
            optionalPrincipal = underlying.authenticate(credentials);
            if (optionalPrincipal.isPresent()) {
                cache.put(credentials, optionalPrincipal);
            }
        }
        return optionalPrincipal;
    } finally {
        context.stop();
    }
}
项目:hesperides    文件:LDAPAuthenticator.java   
@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();
}
项目:hesperides    文件:LDAPAuthenticator.java   
private SearchResult searchUser(final AutoclosableDirContext context, final String username) throws NamingException, AuthenticationException {
    String searchfilter = String.format("(%s=%s)", configuration.getUserNameAttribute(), username);

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> results = context.search(configuration.getUserSearchBase(), searchfilter, searchControls);

    SearchResult searchResult;

    if (results.hasMoreElements()) {
        searchResult = results.nextElement();

        if (results.hasMoreElements()) {
            throw new AuthenticationException("Expected to find only one user for " + username + " but found more results");
        }

    } else {
        throw new AuthenticationException("Unable to authenticate user " + username);
    }

    return searchResult;
}
项目:hesperides    文件:HesperidesApplicationResourceTest.java   
@Before
public void setup() throws AuthenticationException {
    reset(applications);
    reset(applicationSearch);

    final RetryRedisConfiguration retryRedisConfiguration = new RetryRedisConfiguration();
    final HesperidesCacheParameter hesperidesCacheParameter = new HesperidesCacheParameter();

    final HesperidesCacheConfiguration hesperidesCacheConfiguration = new HesperidesCacheConfiguration();
    hesperidesCacheConfiguration.setRedisConfiguration(retryRedisConfiguration);
    hesperidesCacheConfiguration.setPlatformTimeline(hesperidesCacheParameter);
    hesperidesCacheConfiguration.setTemplatePackage(hesperidesCacheParameter);
    hesperidesCacheConfiguration.setNbEventBeforePersiste(10000);

    final HesperidesConfiguration hesperidesConfiguration = new HesperidesConfiguration();
    hesperidesConfiguration.setCacheConfiguration(hesperidesCacheConfiguration);

    applicationsWithEvent = new ApplicationsAggregate(eventBus, eventStore,
            new SnapshotRegistry(poolRedis.getPool()), hesperidesConfiguration);
    poolRedis.reset();
}
项目:dropauth    文件:DropauthAuthenticator.java   
@Override
public Optional<ResourceOwner> authenticate(String tokenValue) throws AuthenticationException {
    try {
        // Resolve the provided Token using the TokenService
        AccessToken token = tokenService.resolveToken(tokenValue);
        // Check if the token is still valid (not expired)
        Date now = new Date();
        if(token.getExpiryDate().compareTo(now) > 0) {
            ResourceOwner resourceOwner = authProvider.identify(token.getOwner());
            return Optional.of(resourceOwner);
        }
        // If this is reached, AuthenticationException is caused
        return Optional.absent();
    } catch (Exception e) {
        return Optional.absent();
    }
}
项目:keywhiz    文件:BcryptAuthenticator.java   
@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);
}
项目:keywhiz    文件:ClientAuthFactory.java   
@Override public Optional<Client> authenticate(String name)
    throws AuthenticationException {
  Optional<Client> optionalClient = clientDAOReadOnly.getClient(name);
  if (optionalClient.isPresent()) {
    Client client = optionalClient.get();
    clientDAOReadWrite.sawClient(client);
    if (client.isEnabled()) {
      return optionalClient;
    } else {
      logger.warn("Client {} authenticated but disabled via DB", client);
      return Optional.empty();
    }
  }

  /*
   * If a client is seen for the first time, authenticated by certificate, and has no DB entry,
   * then a DB entry is created here. The client can be disabled in the future by flipping the
   * 'enabled' field.
   */
  // TODO(justin): Consider making this behavior configurable.
  long clientId = clientDAOReadWrite.createClient(name, "automatic",
      "Client created automatically from valid certificate authentication");
  return Optional.of(clientDAOReadWrite.getClientById(clientId).get());
}
项目:AugumentedSzczecin_java    文件:BasicAuthenticator.java   
@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();
}
项目:dropwizard-auth-jwt    文件:JwtAuthFactoryTest.java   
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);
}
项目:dropwizard-auth-jwt    文件:BaseJwtAuthenticatorTest.java   
@Override
protected Optional<String> validateClaims(JwtClaims jwtClaims) throws AuthenticationException {
    try {
        final String subject = jwtClaims.getSubject();
        if ("good-one".equals(subject)) {
            return Optional.of("good-one");
        }

        if ("bad-one".equals(subject)) {
            throw new AuthenticationException("server ran out of entropy");
        }
    } catch (MalformedClaimException e) {
        return Optional.absent();
    }

    return Optional.absent();
}
项目:pay-publicapi    文件:AccountAuthenticator.java   
@Override
public Optional<Account> authenticate(String bearerToken) throws AuthenticationException {
    Response response = client.target(publicAuthUrl).request()
            .header(AUTHORIZATION, "Bearer " + bearerToken)
            .accept(MediaType.APPLICATION_JSON)
            .get();
    if (response.getStatus() == OK.getStatusCode()) {
        JsonNode responseEntity = response.readEntity(JsonNode.class);
        String accountId = responseEntity.get("account_id").asText();
        String tokenType = Optional.ofNullable(responseEntity.get("token_type"))
                .map(JsonNode::asText).orElse(CARD.toString());
        TokenPaymentType tokenPaymentType = fromString(tokenType);
        return Optional.of(new Account(accountId, tokenPaymentType));
    } else if (response.getStatus() == UNAUTHORIZED.getStatusCode()) {
        response.close();
        return Optional.empty();
    } else {
        response.close();
        logger.warn("Unexpected status code " + response.getStatus() + " from auth.");
        throw new ServiceUnavailableException();
    }
}
项目:oauth2-dropwizard    文件:OAuth2Authenticator.java   
public Optional<User> authenticate(OAuth2Credentials credentials) throws AuthenticationException {
    try {
        AccessToken token;
        if (credentials instanceof OAuth2CookieCredentials) {
            token = ((OAuth2CookieCredentials) credentials).getToken();
        } else {
            token = new AccessToken();
            token.setToken(((OAuth2HeaderCredentials) credentials).getToken());
        }

        TokenValidationResponse tvr = validateToken(token);
        if (!tvr.isValid())
            return Optional.absent();

        String username = tvr.getUserId();
        if (credentials instanceof OAuth2CookieCredentials)
            username = ((OAuth2CookieCredentials) credentials).getUsername();

        return Optional.fromNullable(new User(username, token));
    } catch (Exception ex) {
        log.error("Exception during authentication", ex);
        throw new AuthenticationException("Invalid credentials");
    }
}
项目:log-dropwizard-eureka-mongo-sample    文件:NullAuthProvider.java   
@Override
public T getValue(HttpContext c) {
    try {
        final Optional<T> result = authenticator.authenticate(null);
        if (result.isPresent()) {
            return result.get();
        }
    } catch (AuthenticationException e) {
        LOGGER.warn("Error authenticating credentials", e);
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }


    if (required) {
        throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED)
                .entity("Credentials are required to access this resource.")
                .type(MediaType.TEXT_PLAIN_TYPE)
                .build());
    }
    return null;
}
项目:dropwizard-auth-example    文件:OAuth2Authenticator.java   
@Override
public Optional<User> authenticate(String s) throws AuthenticationException {
    JwtClaims claims;
    try {
        claims = jwtVerifier.authenticate(Jwt.newFromString(s));
    } catch (JwtParseException | JwtVerifyException e) {
        LOG.error("Failed to authenticate token!", e);
        throw new AuthenticationException("Failed to authenticate token!", e);
    }

    Set<String> roles = parseRolesClaim(claims);

    return Optional.of(
            User.newBuilder()
                .withId(claims.getSubject())
                .withOrgId((String) claims.getClaim("orgId"))
                .withRoles(roles)
                .build());
}
项目:dropwizard-api-key-bundle    文件:BasicCredentialsAuthenticator.java   
@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());
}
项目:robe    文件:AuthenticatedWebSocket.java   
@Override
public String onConnect(Session session) {
    for (HttpCookie cookie : session.getUpgradeRequest().getCookies()) {
        if ("auth-token".equals(cookie.getName())) {
            String authToken = cookie.getValue();
            TokenAuthenticator authenticator = getAuthenticator();
            org.hibernate.Session hSession = sessionFactory.openSession();
            ManagedSessionContext.bind(hSession);
            Optional<BasicToken> token;
            try {
                token = authenticator.authenticate(authToken);
            } catch (AuthenticationException e) {
                e.printStackTrace();
                return null;
            }
            if (!token.isPresent()) {
                return null;
            }
            hSession.close();
            return token.get().getUserId();
        }
    }
    return null;
}
项目:robe    文件:AbstractAuthResource.java   
/**
 * Changes the password for the specified user. This requires the current password, as well as
 * the password to replace it with. The new password should be checked against old hashes to be sure the new password does not closely resemble or equal any recent passwords for that UserEntry.
 * Password strength should also be verified.  This new password must be repeated to ensure that the user has typed it in correctly.
 *
 * @param user            the user to change the password for
 * @param currentPassword the current password for the specified user
 * @param newPassword     the new password to use
 * @param newPassword2    a verification copy of the new password
 * @throws io.dropwizard.auth.AuthenticationException if any errors occur
 */
public void changePassword(T user, String currentPassword, String newPassword, String newPassword2) throws AuthenticationException {

    verifyPassword(user, currentPassword);

    if (!newPassword.equals(newPassword2)) {
        throw new AuthenticationException(user.getUsername() + ": New password and re-type password must be same");
    } else if (newPassword.equals(currentPassword)) {
        throw new AuthenticationException(user.getUsername() + ": New password and old password must be different");
    }
    verifyPasswordStrength(currentPassword, newPassword, user);

    Optional<? extends UserEntry> optional = userStore.changePassword(user.getUsername(), newPassword);
    if (!optional.isPresent()) {
        throw new AuthenticationException(user.getUsername() + ": Can't update UserEntry Password");
    }
}
项目:robe    文件:AbstractAuthResource.java   
/**
 * Ensures that the password meets site-specific complexity requirements, like length or number
 * of character sets. This method takes the old password so that the algorithm can analyze the
 * new password to see if it is too similar to the old password. Note that this has to be
 * invoked when the user has entered the old password, as the list of old
 * credentials stored by ESAPI is all hashed.
 * Additionally, the user object is taken in order to verify the password and account name differ.
 *
 * @param oldPassword the old password
 * @param newPassword the new password
 * @param user        the user
 * @throws io.dropwizard.auth.AuthenticationException if newPassword is too similar to oldPassword or if newPassword does not meet complexity requirements
 */
public void verifyPasswordStrength(String oldPassword, String newPassword, T user) throws AuthenticationException {
    List<Rule> rules = getPasswordRules();
    PasswordValidator validator = new PasswordValidator(rules);
    PasswordData passwordData = new PasswordData(new Password(newPassword));
    RuleResult result = validator.validate(passwordData);
    if (!result.isValid()) {
        StringBuilder messages = new StringBuilder();
        for (String msg : validator.getMessages(result)) {
            messages.append(msg).append("\n");
        }
        throw new AuthenticationException(messages.toString());
    }


}
项目:backups    文件:TokenAuthenticator.java   
@Override
public Optional<ClientPermission> authenticate(TokenCredentials tokenCredential) throws AuthenticationException {
    // Check for a service token that matches
    final Optional<ClientPermission> servicePermission = getFromServiceToken(tokenCredential.getService(), tokenCredential.getToken());
    if (servicePermission.isPresent()) {
        return servicePermission;
    }

    // Check for a temporary token that matches, only if this is a read request
    if (tokenCredential.isReadRequest()) {
        final Optional<ClientPermission> temporaryPermission = getFromTemporaryToken(tokenCredential.getService(), tokenCredential.getToken());
        if (temporaryPermission.isPresent()) {
            return temporaryPermission;
        }
    }

    // No permission
    return Optional.absent();
}
项目:restwars    文件:PlayerAuthenticator.java   
@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();
}