Search in sources :

Example 11 with JSONArray

use of com.nimbusds.jose.shaded.json.JSONArray in project PowerNukkitX by BlocklyNukkit.

the class Metrics method getPluginData.

/**
 * Gets the plugin specific data.
 *
 * @return The plugin specific data.
 */
private JSONObject getPluginData() {
    JSONObject data = new JSONObject();
    // Append the name of the server software
    data.put("pluginName", name);
    JSONArray customCharts = new JSONArray();
    for (CustomChart customChart : charts) {
        // Add the data of the custom charts
        JSONObject chart = customChart.getRequestJsonObject();
        if (chart == null) {
            // If the chart is null, we skip it
            continue;
        }
        customCharts.add(chart);
    }
    data.put("customCharts", customCharts);
    return data;
}
Also used : JSONObject(com.nimbusds.jose.shaded.json.JSONObject) JSONArray(com.nimbusds.jose.shaded.json.JSONArray)

Example 12 with JSONArray

use of com.nimbusds.jose.shaded.json.JSONArray in project GeyserConnect by GeyserMC.

the class PacketHandler method handle.

@Override
public boolean handle(LoginPacket packet) {
    masterServer.getLogger().debug("Login: " + packet.toString());
    BedrockPacketCodec packetCodec = MinecraftProtocol.getBedrockCodec(packet.getProtocolVersion());
    if (packetCodec == null) {
        session.setPacketCodec(MinecraftProtocol.DEFAULT_BEDROCK_CODEC);
        String message = "disconnectionScreen.internalError.cantConnect";
        PlayStatusPacket status = new PlayStatusPacket();
        if (packet.getProtocolVersion() > MinecraftProtocol.DEFAULT_BEDROCK_CODEC.getProtocolVersion()) {
            status.setStatus(PlayStatusPacket.Status.LOGIN_FAILED_SERVER_OLD);
            message = "disconnectionScreen.outdatedServer";
        } else if (packet.getProtocolVersion() < MinecraftProtocol.DEFAULT_BEDROCK_CODEC.getProtocolVersion()) {
            status.setStatus(PlayStatusPacket.Status.LOGIN_FAILED_CLIENT_OLD);
            message = "disconnectionScreen.outdatedClient";
        }
        session.sendPacket(status);
        session.disconnect(message);
        return false;
    }
    // Set the session codec
    session.setPacketCodec(packetCodec);
    // Read the raw chain data
    JsonNode rawChainData;
    try {
        rawChainData = OBJECT_MAPPER.readTree(packet.getChainData().toByteArray());
    } catch (IOException e) {
        throw new AssertionError("Unable to read chain data!");
    }
    // Get the parsed chain data
    JsonNode chainData = rawChainData.get("chain");
    if (chainData.getNodeType() != JsonNodeType.ARRAY) {
        throw new AssertionError("Invalid chain data!");
    }
    try {
        // Convert the chainData to a JSONArray
        ObjectReader reader = OBJECT_MAPPER.readerFor(new TypeReference<List<String>>() {
        });
        JSONArray array = new JSONArray();
        array.addAll(reader.readValue(chainData));
        // Verify the chain data
        if (!EncryptionUtils.verifyChain(array)) {
            // Disconnect the client
            session.disconnect("disconnectionScreen.internalError.cantConnect");
            throw new AssertionError("Failed to login, due to invalid chain data!");
        }
        // Parse the signed jws object
        JWSObject jwsObject;
        jwsObject = JWSObject.parse(chainData.get(chainData.size() - 1).asText());
        // Read the JWS payload
        JsonNode payload = OBJECT_MAPPER.readTree(jwsObject.getPayload().toBytes());
        // Check the identityPublicKey is there
        if (payload.get("identityPublicKey").getNodeType() != JsonNodeType.STRING) {
            throw new AssertionError("Missing identity public key!");
        }
        // Create an ECPublicKey from the identityPublicKey
        ECPublicKey identityPublicKey = EncryptionUtils.generateKey(payload.get("identityPublicKey").textValue());
        // Get the skin data to validate the JWS token
        JWSObject skinData = JWSObject.parse(packet.getSkinData().toString());
        if (skinData.verify(new DefaultJWSVerifierFactory().createJWSVerifier(skinData.getHeader(), identityPublicKey))) {
            // Make sure the client sent over the username, xuid and other info
            if (payload.get("extraData").getNodeType() != JsonNodeType.OBJECT) {
                throw new AssertionError("Missing client data");
            }
            // Fetch the client data
            JsonNode extraData = payload.get("extraData");
            AuthData authData = new AuthData(extraData.get("displayName").asText(), UUID.fromString(extraData.get("identity").asText()), extraData.get("XUID").asText());
            // Create a new player and add it to the players list
            player = new Player(authData, session);
            masterServer.getPlayers().add(player);
            player.setChainData(chainData);
            // Store the full client data
            player.setClientData(OBJECT_MAPPER.convertValue(OBJECT_MAPPER.readTree(skinData.getPayload().toBytes()), BedrockClientData.class));
            player.getClientData().setOriginalString(packet.getSkinData().toString());
            // Tell the client we have logged in successfully
            PlayStatusPacket playStatusPacket = new PlayStatusPacket();
            playStatusPacket.setStatus(PlayStatusPacket.Status.LOGIN_SUCCESS);
            session.sendPacket(playStatusPacket);
            // Tell the client there are no resourcepacks
            ResourcePacksInfoPacket resourcePacksInfo = new ResourcePacksInfoPacket();
            session.sendPacket(resourcePacksInfo);
        } else {
            throw new AssertionError("Invalid identity public key!");
        }
    } catch (Exception e) {
        // Disconnect the client
        session.disconnect("disconnectionScreen.internalError.cantConnect");
        throw new AssertionError("Failed to login", e);
    }
    return false;
}
Also used : Player(org.geysermc.connect.utils.Player) AuthData(org.geysermc.geyser.session.auth.AuthData) DefaultJWSVerifierFactory(com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory) JSONArray(com.nimbusds.jose.shaded.json.JSONArray) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) IOException(java.io.IOException) BedrockClientData(org.geysermc.geyser.session.auth.BedrockClientData) ECPublicKey(java.security.interfaces.ECPublicKey) BedrockPacketCodec(com.nukkitx.protocol.bedrock.BedrockPacketCodec) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) List(java.util.List) JWSObject(com.nimbusds.jose.JWSObject)

Example 13 with JSONArray

use of com.nimbusds.jose.shaded.json.JSONArray in project spring-security by spring-projects.

the class ClaimTypeConverterTests method convertWhenAllClaimsRequireConversionThenConvertAll.

@Test
public void convertWhenAllClaimsRequireConversionThenConvertAll() throws Exception {
    Instant instant = Instant.now();
    URL url = new URL("https://localhost");
    List<Number> listNumber = Lists.list(1, 2, 3, 4);
    List<String> listString = Lists.list("1", "2", "3", "4");
    Map<Integer, Object> mapIntegerObject = new HashMap<>();
    mapIntegerObject.put(1, "value1");
    Map<String, Object> mapStringObject = new HashMap<>();
    mapStringObject.put("1", "value1");
    JSONArray jsonArray = new JSONArray();
    jsonArray.add("1");
    List<String> jsonArrayListString = Lists.list("1");
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("1", "value1");
    Map<String, Object> jsonObjectMap = Maps.newHashMap("1", "value1");
    Map<String, Object> claims = new HashMap<>();
    claims.put(STRING_CLAIM, Boolean.TRUE);
    claims.put(BOOLEAN_CLAIM, "true");
    claims.put(INSTANT_CLAIM, instant.toString());
    claims.put(URL_CLAIM, url.toExternalForm());
    claims.put(COLLECTION_STRING_CLAIM, listNumber);
    claims.put(LIST_STRING_CLAIM, listNumber);
    claims.put(MAP_STRING_OBJECT_CLAIM, mapIntegerObject);
    claims.put(JSON_ARRAY_CLAIM, jsonArray);
    claims.put(JSON_OBJECT_CLAIM, jsonObject);
    claims = this.claimTypeConverter.convert(claims);
    assertThat(claims.get(STRING_CLAIM)).isEqualTo("true");
    assertThat(claims.get(BOOLEAN_CLAIM)).isEqualTo(Boolean.TRUE);
    assertThat(claims.get(INSTANT_CLAIM)).isEqualTo(instant);
    assertThat(claims.get(URL_CLAIM)).isEqualTo(url);
    assertThat(claims.get(COLLECTION_STRING_CLAIM)).isEqualTo(listString);
    assertThat(claims.get(LIST_STRING_CLAIM)).isEqualTo(listString);
    assertThat(claims.get(MAP_STRING_OBJECT_CLAIM)).isEqualTo(mapStringObject);
    assertThat(claims.get(JSON_ARRAY_CLAIM)).isEqualTo(jsonArrayListString);
    assertThat(claims.get(JSON_OBJECT_CLAIM)).isEqualTo(jsonObjectMap);
}
Also used : HashMap(java.util.HashMap) Instant(java.time.Instant) JSONArray(com.nimbusds.jose.shaded.json.JSONArray) URL(java.net.URL) JSONObject(com.nimbusds.jose.shaded.json.JSONObject) JSONObject(com.nimbusds.jose.shaded.json.JSONObject) Test(org.junit.jupiter.api.Test)

Example 14 with JSONArray

use of com.nimbusds.jose.shaded.json.JSONArray in project itpark2021 by vitr1988.

the class JwtHelper method parseToken.

@SneakyThrows
public AuthorizedUser parseToken(String token) {
    if (StringUtils.isEmpty(token)) {
        return null;
    }
    final JWTClaimsSet jwtClaims;
    final SignedJWT decodedJWT = SignedJWT.parse(token);
    if (decodedJWT.verify(jwsVerifier) && isValid(jwtClaims = decodedJWT.getJWTClaimsSet())) {
        final String login = this.<String>getClaim(jwtClaims, "login").filter(StringUtils::isNotEmpty).orElseThrow();
        final String[] userRights = this.<JSONArray>getClaim(jwtClaims, "rights").map(list -> list.stream().toArray(String[]::new)).orElse(new String[] {});
        return new AuthorizedUser(login, userRights);
    }
    throw new IllegalArgumentException();
}
Also used : MACSigner(com.nimbusds.jose.crypto.MACSigner) JWSVerifier(com.nimbusds.jose.JWSVerifier) SneakyThrows(lombok.SneakyThrows) Date(java.util.Date) JOSEException(com.nimbusds.jose.JOSEException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) Instant(java.time.Instant) JWSHeader(com.nimbusds.jose.JWSHeader) SignedJWT(com.nimbusds.jwt.SignedJWT) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) MACVerifier(com.nimbusds.jose.crypto.MACVerifier) Component(org.springframework.stereotype.Component) JWSSigner(com.nimbusds.jose.JWSSigner) ChronoUnit(java.time.temporal.ChronoUnit) Pair(org.apache.commons.lang3.tuple.Pair) Duration(java.time.Duration) Optional(java.util.Optional) AuthorizedUser(lesson38.security.dto.AuthorizedUser) JSONArray(com.nimbusds.jose.shaded.json.JSONArray) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) AuthorizedUser(lesson38.security.dto.AuthorizedUser) JSONArray(com.nimbusds.jose.shaded.json.JSONArray) SignedJWT(com.nimbusds.jwt.SignedJWT) SneakyThrows(lombok.SneakyThrows)

Aggregations

JSONArray (com.nimbusds.jose.shaded.json.JSONArray)14 JSONObject (com.nimbusds.jose.shaded.json.JSONObject)9 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)3 SignedJWT (com.nimbusds.jwt.SignedJWT)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 JOSEException (com.nimbusds.jose.JOSEException)2 JWSHeader (com.nimbusds.jose.JWSHeader)2 MACSigner (com.nimbusds.jose.crypto.MACSigner)2 Instant (java.time.Instant)2 List (java.util.List)2 Optional (java.util.Optional)2 Test (org.junit.jupiter.api.Test)2 OidcReactiveApiSecurityConfig (com.c4_soft.springaddons.security.oauth2.config.reactive.OidcReactiveApiSecurityConfig)1 OidcServletApiSecurityConfig (com.c4_soft.springaddons.security.oauth2.config.synchronised.OidcServletApiSecurityConfig)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectReader (com.fasterxml.jackson.databind.ObjectReader)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 JWSObject (com.nimbusds.jose.JWSObject)1 JWSSigner (com.nimbusds.jose.JWSSigner)1