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.entcore.auth.controllers.SamlController.java

License:Open Source License

@Get("/saml/metadata/:idp")
public void idpGar(HttpServerRequest request) {
    JsonObject idpConfig = config.getJsonObject("idp-metadata-mapping", new JsonObject());
    String idpParam = request.getParam("idp");
    if (!idpConfig.isEmpty() && idpConfig.containsKey(idpParam)) {
        request.response().sendFile(idpConfig.getString(idpParam));
    } else {/*from   w w  w.  j a v a 2s  .  c  o  m*/
        request.response().setStatusCode(404).setStatusMessage("idp not found").end();
    }
}

From source file:org.entcore.auth.controllers.SamlController.java

License:Open Source License

/**
 * Generate HTML auto-submit FORM with samlResponse and render the page
 * @param samlResponse64 base64 SAMLResponse
 * @param destination the recipient (SP acs)
 *//*from w w  w  . j av  a 2  s  .co m*/
private void renderSamlResponse(UserInfos user, String samlResponse64, String providerId, String destination,
        HttpServerRequest request) {
    JsonObject paramsFED = new JsonObject();
    paramsFED.put("SAMLResponse", samlResponse64);
    JsonObject relayStateMap = config.getJsonObject("relay-state");
    if (relayStateMap != null) {
        String relayState = relayStateMap.getString(providerId);
        if (relayState != null) {
            paramsFED.put("RelayState", relayState);
        } else {
            log.error("Error loading relay-state for providerId : " + providerId);
        }
    } else {
        log.error("Error loading relay-state properties.");
    }
    paramsFED.put("Destination", destination);
    renderView(request, paramsFED, "fed.html", null);
}

From source file:org.entcore.auth.controllers.SamlController.java

License:Open Source License

@Post("/saml/acs")
public void acs(final HttpServerRequest request) {
    validateResponseAndGetAssertion(request, new Handler<Assertion>() {
        @Override//  w  ww .j a  va 2s  . c  o m
        public void handle(final Assertion assertion) {
            SamlServiceProvider sp = spFactory.serviceProvider(assertion);
            sp.execute(assertion, new Handler<Either<String, Object>>() {
                @Override
                public void handle(final Either<String, Object> event) {
                    if (event.isLeft()) {
                        loginResult(request, "fed.auth.error.user.not.found");
                    } else {
                        final String nameIdFromAssertion = getNameId(assertion);
                        final String sessionIndex = getSessionId(assertion);
                        if (log.isDebugEnabled()) {
                            log.debug("NameID : " + nameIdFromAssertion);
                            log.debug("SessionIndex : " + sessionIndex);
                        }
                        if (nameIdFromAssertion == null || sessionIndex == null
                                || nameIdFromAssertion.trim().isEmpty() || sessionIndex.trim().isEmpty()) {
                            redirect(request, LOGIN_PAGE);
                            return;
                        }

                        // if user is already authenticated in the ENT through the ENT login page, we do not authenticate him again
                        // because this will store the "nameid"

                        // ALGORITHM RULE :
                        // if user has "nameId" : it means user connected first with a federated idp
                        // else he connected to the ENT through the ENT login page
                        // this way we know if we need to disonnect/redirect the user to the federated login/home page OR
                        // if we only disconnect him to the ENT (no nameid)
                        final String sessionId = CookieHelper.getInstance().getSigned("oneSessionId", request);

                        //                     final JsonObject query = new JsonObject().put("_id", sessionId);
                        //                     mongo.findOne(SESSIONS_COLLECTION, query, new io.vertx.core.Handler<Message<JsonObject>>() {
                        federationService.getMongoDbSession(sessionId,
                                new io.vertx.core.Handler<Message<JsonObject>>() {
                                    @Override
                                    public void handle(Message<JsonObject> eventMongo) {
                                        JsonObject res = eventMongo.body().getJsonObject("result");
                                        String userId;
                                        if ("ok".equals(eventMongo.body().getString("status")) && res != null
                                                && (userId = res.getString("userId")) != null
                                                && !userId.trim().isEmpty()) {

                                            String nameID = res.getString("NameID");

                                            String userIdAssertion = null;
                                            if (event.right().getValue() != null
                                                    && event.right().getValue() instanceof JsonObject) {
                                                userIdAssertion = ((JsonObject) event.right().getValue())
                                                        .getString("id");
                                            }

                                            // no NameID and same userId : user already connected through IDP ENT
                                            if ((nameID == null || nameID.trim().isEmpty())
                                                    && userIdAssertion != null
                                                    && userIdAssertion.equals(userId)) {
                                                redirect(request, "/");
                                            } else {
                                                endAcs(request, event, sessionIndex, nameIdFromAssertion);
                                            }
                                        } else {
                                            endAcs(request, event, sessionIndex, nameIdFromAssertion);
                                        }
                                    }
                                });
                    }
                }
            });
        }
    });
}

From source file:org.entcore.auth.controllers.SamlController.java

License:Open Source License

@Override
protected void afterDropSession(JsonObject event, final HttpServerRequest request, UserInfos user,
        final String c) {
    request.headers().remove("Cookie");
    event.put("action", "generate-slo-request");
    event.put("IDP", (String) user.getOtherProperties().get("federatedIDP"));
    if (log.isDebugEnabled()) {
        log.debug("Session metadata : " + event.encodePrettily());
    }/*from w w  w.ja  v  a 2  s  .co m*/

    String nameID = event.getString("NameID");
    if (nameID != null && !nameID.isEmpty()) {
        if (softSlo) {
            Matcher academyMatcher = NAME_QUALIFIER_PATTERN.matcher(nameID);
            if (academyMatcher.find()) {
                String nameQualifier = academyMatcher.group(1);
                JsonObject confSoftSlo = config.getJsonObject("soft-slo-redirect");
                if (confSoftSlo != null) {
                    String redirectIDP = confSoftSlo.getString(nameQualifier);
                    if (redirectIDP != null) {
                        redirect(request, redirectIDP, "");
                    } else {
                        log.error("Error loading soft-slo-redirect for IDP : " + nameQualifier);
                        redirect(request, LOGIN_PAGE);
                    }
                } else {
                    log.error("Error loading soft-slo-redirect properties.");
                    redirect(request, LOGIN_PAGE);
                }
            }
        } else {
            // normal slo
            vertx.eventBus().send("saml", event, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
                @Override
                public void handle(Message<JsonObject> event) {
                    if (log.isDebugEnabled()) {
                        log.debug("slo request : " + event.body().encodePrettily());
                    }
                    String slo = event.body().getString("slo");
                    try {
                        if (c != null && !c.isEmpty()) {
                            slo = c + URLEncoder.encode(slo, "UTF-8");
                        } else {
                            slo = URLEncoder.encode(slo, "UTF-8");
                        }
                    } catch (UnsupportedEncodingException e) {
                        log.error(e.getMessage(), e);
                    }
                    AuthController.logoutCallback(request, slo, config, eb);
                }
            }));
        }
    } else {
        AuthController.logoutCallback(request, null, config, eb);
    }
}

From source file:org.entcore.auth.controllers.SamlController.java

License:Open Source License

private JsonObject getUsersWithSignatures(JsonArray array, String sessionIndex, String nameId)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    for (Object o : array) {
        if (!(o instanceof JsonObject))
            continue;
        JsonObject j = (JsonObject) o;
        j.put("key", HmacSha1.sign(sessionIndex + nameId + j.getString("login") + j.getString("id"), signKey));
        j.put("nameId", nameId);
        j.put("sessionIndex", sessionIndex);
    }/*from w w w .j  ava2s.  com*/
    return new JsonObject().put("users", array);
}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

private void checkPassword(JsonArray result, String password, String username, Handler<String> handler) {
    JsonObject r = result.getJsonObject(0);
    String dbPassword;/* w w w. ja v a 2  s . c  o m*/
    if (r != null && (dbPassword = r.getString("password")) != null
            && !getOrElse(r.getBoolean("blockedProfile"), false)) {
        boolean success = false;
        String hash = null;
        try {
            switch (dbPassword.length()) {
            case 32: // md5
                hash = Md5.hash(password);
                break;
            case 64: // sha-256
                hash = Sha256.hash(password);
                break;
            default: // BCrypt
                success = BCrypt.checkpw(password, dbPassword);
            }
            if (!success && hash != null) {
                success = !dbPassword.trim().isEmpty() && dbPassword.equalsIgnoreCase(hash);
                if (success) {
                    upgradeOldPassword(username, password);
                }
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
        }
        if (success) {
            handler.handle(r.getString("userId"));
        } else {
            handler.handle(null);
        }
    } else {
        handler.handle(null);
    }
}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

@Override
public void createOrUpdateAccessToken(final AuthInfo authInfo, final Handler<AccessToken> handler) {
    if (authInfo != null) {
        final JsonObject query = new JsonObject().put("authId", authInfo.getId());
        mongo.count(ACCESS_TOKEN_COLLECTION, query, new io.vertx.core.Handler<Message<JsonObject>>() {
            @Override/*from www.  j ava2 s  . c  o  m*/
            public void handle(Message<JsonObject> event) {
                if ("ok".equals(event.body().getString("status")) && (event.body().getInteger("count", 1) == 0
                        || isNotEmpty(authInfo.getRefreshToken()))) {
                    final JsonObject token = new JsonObject().put("authId", authInfo.getId())
                            .put("token", UUID.randomUUID().toString()).put("createdOn", MongoDb.now())
                            .put("expiresIn", 3600);
                    if (openIdConnectService != null && authInfo.getScope() != null
                            && authInfo.getScope().contains("openid")) {
                        //"2.0".equals(RequestUtils.getAcceptVersion(getRequest().getHeader("Accept")))) {
                        openIdConnectService.generateIdToken(authInfo.getUserId(), authInfo.getClientId(),
                                new io.vertx.core.Handler<AsyncResult<String>>() {
                                    @Override
                                    public void handle(AsyncResult<String> ar) {
                                        if (ar.succeeded()) {
                                            token.put("id_token", ar.result());
                                            persistToken(token);
                                        } else {
                                            log.error("Error generating id_token.", ar.cause());
                                            handler.handle(null);
                                        }
                                    }
                                });
                    } else {
                        persistToken(token);
                    }
                } else { // revoke existing token and code with same authId
                    mongo.delete(ACCESS_TOKEN_COLLECTION, query);
                    mongo.delete(AUTH_INFO_COLLECTION, new JsonObject().put("_id", authInfo.getId()));
                    handler.handle(null);
                }
            }

            private void persistToken(final JsonObject token) {
                mongo.save(ACCESS_TOKEN_COLLECTION, token, new io.vertx.core.Handler<Message<JsonObject>>() {

                    @Override
                    public void handle(Message<JsonObject> res) {
                        if ("ok".equals(res.body().getString("status"))) {
                            AccessToken t = new AccessToken();
                            t.setAuthId(authInfo.getId());
                            t.setToken(token.getString("token"));
                            t.setCreatedOn(new Date(token.getJsonObject("createdOn").getLong("$date")));
                            t.setExpiresIn(3600);
                            if (token.containsKey("id_token")) {
                                t.setIdToken(token.getString("id_token"));
                            }
                            handler.handle(t);
                        } else {
                            handler.handle(null);
                        }
                    }
                });
            }
        });
    } else {
        handler.handle(null);
    }
}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

@Override
public void getAuthInfoByCode(String code, final Handler<AuthInfo> handler) {
    if (code != null && !code.trim().isEmpty()) {
        JsonObject query = new JsonObject().put("code", code).put("createdAt", new JsonObject().put("$gte",
                new JsonObject().put("$date", System.currentTimeMillis() - CODE_EXPIRES)));
        mongo.findOne(AUTH_INFO_COLLECTION, query, new io.vertx.core.Handler<Message<JsonObject>>() {

            @Override//  w  w  w. ja  va  2s .c o m
            public void handle(Message<JsonObject> res) {
                JsonObject r = res.body().getJsonObject("result");
                if ("ok".equals(res.body().getString("status")) && r != null && r.size() > 0) {
                    r.put("id", r.getString("_id"));
                    r.remove("_id");
                    r.remove("createdAt");
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        handler.handle(mapper.readValue(r.encode(), AuthInfo.class));
                    } catch (IOException e) {
                        handler.handle(null);
                    }
                } else {
                    handler.handle(null);
                }
            }
        });
    } else {
        handler.handle(null);
    }
}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

@Override
public void getAuthInfoByRefreshToken(String refreshToken, final Handler<AuthInfo> handler) {
    if (refreshToken != null && !refreshToken.trim().isEmpty()) {
        JsonObject query = new JsonObject().put("refreshToken", refreshToken);
        mongo.findOne(AUTH_INFO_COLLECTION, query, new io.vertx.core.Handler<Message<JsonObject>>() {

            @Override/* w w  w.  ja  v  a 2  s . co  m*/
            public void handle(Message<JsonObject> res) {
                if ("ok".equals(res.body().getString("status"))) {
                    JsonObject r = res.body().getJsonObject("result");
                    if (r == null) {
                        handler.handle(null);
                        return;
                    }
                    r.put("id", r.getString("_id"));
                    r.remove("_id");
                    r.remove("createdAt");
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        handler.handle(mapper.readValue(r.encode(), AuthInfo.class));
                    } catch (IOException e) {
                        handler.handle(null);
                    }
                } else {
                    handler.handle(null);
                }
            }
        });
    } else {
        handler.handle(null);
    }
}

From source file:org.entcore.auth.oauth.OAuthDataHandler.java

License:Open Source License

@Override
public void getAccessToken(String token, final Handler<AccessToken> handler) {
    if (token != null && !token.trim().isEmpty()) {
        JsonObject query = new JsonObject().put("token", token);
        mongo.findOne(ACCESS_TOKEN_COLLECTION, query, new io.vertx.core.Handler<Message<JsonObject>>() {

            @Override/*from www  .j a  v  a 2s  . co m*/
            public void handle(Message<JsonObject> res) {
                JsonObject r = res.body().getJsonObject("result");
                if ("ok".equals(res.body().getString("status")) && r != null && r.size() > 0) {
                    AccessToken t = new AccessToken();
                    t.setAuthId(r.getString("authId"));
                    t.setToken(r.getString("token"));
                    t.setCreatedOn(MongoDb.parseIsoDate(r.getJsonObject("createdOn")));
                    t.setExpiresIn(r.getInteger("expiresIn"));
                    handler.handle(t);
                } else {
                    handler.handle(null);
                }
            }
        });
    } else {
        handler.handle(null);
    }
}