Example usage for io.vertx.core.json JsonObject getString

List of usage examples for io.vertx.core.json JsonObject getString

Introduction

In this page you can find the example usage for io.vertx.core.json JsonObject getString.

Prototype

public String getString(String key) 

Source Link

Document

Get the string value with the specified key, special cases are addressed for extended JSON types Instant , byte[] and Enum which can be converted to String.

Usage

From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java

License:Open Source License

private JsonObject getCredentials(final String tenantId, final String authId, final String type) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(authId);
    Objects.requireNonNull(type);

    final Map<String, JsonArray> credentialsForTenant = credentials.get(tenantId);
    if (credentialsForTenant != null) {
        JsonArray authIdCredentials = credentialsForTenant.get(authId);
        if (authIdCredentials == null) {
            return null;
        }/*from  w  ww.jav a 2s.  c om*/

        for (Object authIdCredentialEntry : authIdCredentials) {
            JsonObject authIdCredential = (JsonObject) authIdCredentialEntry;
            // return the first matching type entry for this authId
            if (type.equals(authIdCredential.getString(FIELD_TYPE))) {
                return authIdCredential;
            }
        }
    }
    return null;
}

From source file:org.eclipse.hono.deviceregistry.FileBasedRegistrationService.java

License:Open Source License

Future<Void> loadRegistrationData() {
    Future<Void> result = Future.future();

    if (getConfig().getFilename() == null) {
        result.fail(new IllegalStateException("device identity filename is not set"));
    } else {/* ww w.  j av a2s.co m*/

        final FileSystem fs = vertx.fileSystem();
        log.debug("trying to load device registration information from file {}", getConfig().getFilename());
        if (fs.existsBlocking(getConfig().getFilename())) {
            final AtomicInteger deviceCount = new AtomicInteger();
            fs.readFile(getConfig().getFilename(), readAttempt -> {
                if (readAttempt.succeeded()) {
                    JsonArray allObjects = new JsonArray(new String(readAttempt.result().getBytes()));
                    for (Object obj : allObjects) {
                        JsonObject tenant = (JsonObject) obj;
                        String tenantId = tenant.getString(FIELD_TENANT);
                        log.debug("loading devices for tenant [{}]", tenantId);
                        Map<String, JsonObject> deviceMap = new HashMap<>();
                        for (Object deviceObj : tenant.getJsonArray(ARRAY_DEVICES)) {
                            JsonObject device = (JsonObject) deviceObj;
                            String deviceId = device.getString(FIELD_DEVICE_ID);
                            log.debug("loading device [{}]", deviceId);
                            deviceMap.put(deviceId, device.getJsonObject(FIELD_DATA));
                            deviceCount.incrementAndGet();
                        }
                        identities.put(tenantId, deviceMap);
                    }
                    log.info("successfully loaded {} device identities from file [{}]", deviceCount.get(),
                            getConfig().getFilename());
                    result.complete();
                } else {
                    log.warn("could not load device identities from file [{}]", getConfig().getFilename());
                    result.fail(readAttempt.cause());
                }
            });
        } else {
            log.debug("device identity file [{}] does not exist (yet)", getConfig().getFilename());
            result.complete();
        }
    }
    return result;
}

From source file:org.eclipse.hono.server.HonoSaslAuthenticator.java

License:Open Source License

private void evaluatePlainResponse(final Handler<Boolean> completionHandler) {

    byte[] saslResponse = new byte[sasl.pending()];
    sasl.recv(saslResponse, 0, saslResponse.length);

    final DeliveryOptions options = new DeliveryOptions().setSendTimeout(AUTH_REQUEST_TIMEOUT_MILLIS);
    final JsonObject authenticationRequest = getAuthenticationRequest(MECHANISM_PLAIN, saslResponse);
    vertx.eventBus().send(EVENT_BUS_ADDRESS_AUTHENTICATION_IN, authenticationRequest, options, reply -> {
        if (reply.succeeded()) {
            JsonObject result = (JsonObject) reply.result().body();
            LOG.debug("received result of successful authentication request: {}", result);
            addPrincipal(result.getString(FIELD_AUTHORIZATION_ID));
        } else {/*from ww  w .ja v  a 2 s  . c  o  m*/
            LOG.debug("authentication of client failed", reply.cause());
            sasl.done(SaslOutcome.PN_SASL_AUTH);
        }
        completionHandler.handle(true);
    });
}

From source file:org.eclipse.hono.service.auth.AbstractHonoAuthenticationService.java

License:Open Source License

/**
 * The authentication request is required to contain the SASL mechanism in property {@link AuthenticationConstants#FIELD_MECHANISM}
 * and the client's SASL response (Base64 encoded byte array) in property {@link AuthenticationConstants#FIELD_SASL_RESPONSE}.
 * When the mechanism is {@linkplain AuthenticationConstants#MECHANISM_EXTERNAL EXTERNAL}, the request must also contain
 * the <em>subject</em> distinguished name of the verified client certificate in property {@link AuthenticationConstants#FIELD_SUBJECT_DN}.
 * <p>/* w w w  .  ja v a 2  s  .c om*/
 * An example request for a client using SASL EXTERNAL wishing to act as <em>NEW_IDENTITY</em> instead of <em>ORIG_IDENTITY</em>
 * looks like this:
 * <pre>
 * {
 *   "mechanism": "EXTERNAL",
 *   "sasl-response": "TkVXX0lERU5USVRZ",  // the Base64 encoded UTF-8 representation of "NEW_IDENTITY"
 *   "subject-dn": "CN=ORIG_IDENTITY" // the subject Distinguished Name from the verified client certificate
 * }
 * </pre>
 */
@Override
public final void authenticate(final JsonObject authRequest,
        final Handler<AsyncResult<HonoUser>> resultHandler) {

    final String mechanism = Objects.requireNonNull(authRequest)
            .getString(AuthenticationConstants.FIELD_MECHANISM);
    log.debug("received authentication request [mechanism: {}]", mechanism);

    if (AuthenticationConstants.MECHANISM_PLAIN.equals(mechanism)) {

        byte[] saslResponse = authRequest.getBinary(AuthenticationConstants.FIELD_SASL_RESPONSE, new byte[0]);

        try {
            String[] fields = readFields(saslResponse);
            String authzid = fields[0];
            String authcid = fields[1];
            String pwd = fields[2];
            log.debug("processing PLAIN authentication request [authzid: {}, authcid: {}, pwd: *****]", authzid,
                    authcid);
            verifyPlain(authzid, authcid, pwd, resultHandler);
        } catch (CredentialException e) {
            // response did not contain expected values
            resultHandler.handle(Future.failedFuture(e));
        }

    } else if (AuthenticationConstants.MECHANISM_EXTERNAL.equals(mechanism)) {

        final String authzid = new String(authRequest.getBinary(AuthenticationConstants.FIELD_SASL_RESPONSE),
                StandardCharsets.UTF_8);
        final String subject = authRequest.getString(AuthenticationConstants.FIELD_SUBJECT_DN);
        log.debug("processing EXTERNAL authentication request [Subject DN: {}]", subject);
        verifyExternal(authzid, subject, resultHandler);

    } else {
        resultHandler.handle(Future.failedFuture("unsupported SASL mechanism"));
    }
}

From source file:org.eclipse.hono.service.auth.BaseAuthorizationService.java

License:Open Source License

private void processMessage(final Message<JsonObject> message) {
    final JsonObject body = message.body();
    final String authSubject = body.getString(AuthorizationConstants.AUTH_SUBJECT_FIELD);
    final HonoUser user = new HonoUser() {

        @Override//from  w  w  w .jav  a 2s  .c o  m
        public String getName() {
            return authSubject;
        }

        @Override
        public Authorities getAuthorities() {
            return null;
        }

        @Override
        public String getToken() {
            return null;
        }

        @Override
        public boolean isExpired() {
            return false;
        }
    };
    final Activity permission = Activity.valueOf(body.getString(AuthorizationConstants.PERMISSION_FIELD));
    final ResourceIdentifier resource = ResourceIdentifier
            .fromString(body.getString(AuthorizationConstants.RESOURCE_FIELD));

    isAuthorized(user, resource, permission).setHandler(authAttempt -> {
        boolean hasPermission = false;
        if (authAttempt.succeeded()) {
            hasPermission = authAttempt.result();
        }
        LOG.debug("subject [{}] is {}allowed to {} on resource [{}]", authSubject, hasPermission ? "" : "not ",
                permission, resource);
        message.reply(hasPermission ? AuthorizationConstants.ALLOWED : AuthorizationConstants.DENIED);
    });
}

From source file:org.eclipse.hono.service.auth.device.UsernamePasswordAuthProvider.java

License:Open Source License

/**
 * Creates a {@link UsernamePasswordCredentials} instance from auth info provided by a
 * device./*from   w  w  w . j  a va 2s  . c  o m*/
 * <p>
 * The JSON object passed in is required to contain a <em>username</em> and a
 * <em>password</em> property.
 * 
 * @param authInfo The credentials provided by the device.
 * @return The {@link UsernamePasswordCredentials} instance created from the auth info or
 *         {@code null} if the auth info does not contain the required information.
 * @throws NullPointerException if the auth info is {@code null}.
 */
@Override
protected DeviceCredentials getCredentials(final JsonObject authInfo) {

    try {
        final String username = authInfo.getString("username");
        final String password = authInfo.getString("password");
        if (username == null || password == null) {
            return null;
        } else {
            return UsernamePasswordCredentials.create(username, password, config.isSingleTenant());
        }
    } catch (ClassCastException e) {
        return null;
    }
}

From source file:org.eclipse.hono.service.auth.device.UsernamePasswordCredentials.java

License:Open Source License

/**
 * Matches the credentials against a given secret.
 * <p>/*from   w w  w .  j  a  va  2  s .co  m*/
 * The secret is expected to be of type <em>hashed-password</em> as defined by
 * <a href="https://www.eclipse.org/hono/api/Credentials-API/">Hono's Credentials API</a>.
 * 
 * @param candidateSecret The secret to match against.
 * @return {@code true} if the credentials match the secret.
 */
@Override
public boolean matchesCredentials(final JsonObject candidateSecret) {

    try {
        final String pwdHash = candidateSecret.getString(CredentialsConstants.FIELD_SECRETS_PWD_HASH);
        if (pwdHash == null) {
            LOG.debug("candidate hashed-password secret does not contain a pwd hash");
            return false;
        }

        final byte[] hashedPasswordOnRecord = Base64.getDecoder().decode(pwdHash);

        byte[] salt = null;
        final String encodedSalt = candidateSecret.getString(CredentialsConstants.FIELD_SECRETS_SALT);
        // the salt is optional so decodedSalt may stay null if salt was not found
        if (encodedSalt != null) {
            salt = Base64.getDecoder().decode(encodedSalt);
        }

        final String hashFunction = candidateSecret.getString(CredentialsConstants.FIELD_SECRETS_HASH_FUNCTION,
                CredentialsConstants.DEFAULT_HASH_FUNCTION);

        return checkPassword(hashFunction, salt, hashedPasswordOnRecord);

    } catch (final IllegalArgumentException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("cannot decode malformed Base64 encoded property", e);
        }
        return false;
    } catch (final ClassCastException e) {
        // one or more of the properties are not of expected type
        if (LOG.isDebugEnabled()) {
            LOG.debug(
                    "cannot process malformed candidate hashed-password secret returned by Credentials service [{}]",
                    candidateSecret.encodePrettily());
        }
        return false;
    }
}

From source file:org.eclipse.hono.service.auth.device.X509AuthProvider.java

License:Open Source License

/**
 * Creates a {@link SubjectDnCredentials} instance from information provided by a
 * device in its client (X.509) certificate.
 * <p>/*from  w w w  . j  a va 2 s .  c o  m*/
 * The JSON object passed in is required to contain a <em>subject-dn</em> property.
 * If the <em>singleTenant</em> service config property is {@code false}, then the
 * object is also required to contain a <em>tenant-id</em> property, otherwise
 * the default tenant is used.
 * 
 * @param authInfo The authentication information provided by the device.
 * @return The credentials or {@code null} if the authentication information
 *         does not contain a tenant ID and subject DN.
 * @throws NullPointerException if the authentication info is {@code null}.
 */
@Override
protected DeviceCredentials getCredentials(final JsonObject authInfo) {

    Objects.requireNonNull(authInfo);
    try {
        final String tenantId = Optional
                .ofNullable(authInfo.getString(CredentialsConstants.FIELD_PAYLOAD_TENANT_ID)).orElseGet(() -> {
                    if (config.isSingleTenant()) {
                        return Constants.DEFAULT_TENANT;
                    } else {
                        return null;
                    }
                });
        final String subjectDn = authInfo.getString(CredentialsConstants.FIELD_PAYLOAD_SUBJECT_DN);
        if (tenantId == null || subjectDn == null) {
            return null;
        } else {
            return SubjectDnCredentials.create(tenantId, subjectDn);
        }
    } catch (ClassCastException e) {
        return null;
    }
}

From source file:org.eclipse.hono.service.auth.impl.FileBasedAuthenticationService.java

License:Open Source License

private JsonObject getUser(final String authenticationId, final String mechanism) {
    JsonObject result = users.get(authenticationId);
    if (result != null && mechanism.equals(result.getString(FIELD_MECHANISM))) {
        return result;
    } else {/*from ww w  .  j a  v  a 2s .co m*/
        return null;
    }
}

From source file:org.eclipse.hono.service.auth.impl.FileBasedAuthenticationService.java

License:Open Source License

private Authorities toAuthorities(final JsonArray authorities) {

    AuthoritiesImpl result = new AuthoritiesImpl();
    Objects.requireNonNull(authorities).stream().filter(obj -> obj instanceof JsonObject).forEach(obj -> {
        final JsonObject authSpec = (JsonObject) obj;
        final JsonArray activities = authSpec.getJsonArray(FIELD_ACTIVITIES, new JsonArray());
        final String resource = authSpec.getString(FIELD_RESOURCE);
        final String operation = authSpec.getString(FIELD_OPERATION);
        if (resource != null) {
            List<Activity> activityList = new ArrayList<>();
            activities.forEach(s -> {
                Activity act = Activity.valueOf((String) s);
                if (act != null) {
                    activityList.add(act);
                }//from  ww w.ja  v  a  2s  . co m
            });
            result.addResource(resource, activityList.toArray(new Activity[activityList.size()]));
        } else if (operation != null) {
            String[] parts = operation.split(":", 2);
            if (parts.length == 2) {
                result.addOperation(parts[0], parts[1]);
            } else {
                log.debug("ignoring malformed operation spec [{}], operation name missing", operation);
            }
        } else {
            throw new IllegalArgumentException("malformed authorities");
        }
    });
    return result;
}