Java Code Examples for com.nimbusds.jose.JWSObject#parse()

The following examples show how to use com.nimbusds.jose.JWSObject#parse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PacketHandler.java    From BedrockConnect with GNU General Public License v3.0 7 votes vote down vote up
private static boolean validateChainData(JsonNode data) throws Exception {
    ECPublicKey lastKey = null;
    boolean validChain = false;
    for (JsonNode node : data) {
        JWSObject jwt = JWSObject.parse(node.asText());

        if (!validChain) {
            validChain = verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());
        }

        if (lastKey != null) {
            verifyJwt(jwt, lastKey);
        }

        JsonNode payloadNode = Server.JSON_MAPPER.readTree(jwt.getPayload().toString());
        JsonNode ipkNode = payloadNode.get("identityPublicKey");
        Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain");
        lastKey = EncryptionUtils.generateKey(ipkNode.asText());
    }
    return validChain;
}
 
Example 2
Source File: LoginEncryptionUtils.java    From Geyser with MIT License 6 votes vote down vote up
private static boolean validateChainData(JsonNode data) throws Exception {
    ECPublicKey lastKey = null;
    boolean validChain = false;
    for (JsonNode node : data) {
        JWSObject jwt = JWSObject.parse(node.asText());

        if (!validChain) {
            validChain = EncryptionUtils.verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());
        }

        if (lastKey != null) {
            EncryptionUtils.verifyJwt(jwt, lastKey);
        }

        JsonNode payloadNode = JSON_MAPPER.readTree(jwt.getPayload().toString());
        JsonNode ipkNode = payloadNode.get("identityPublicKey");
        Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain");
        lastKey = EncryptionUtils.generateKey(ipkNode.asText());
    }
    return validChain;
}
 
Example 3
Source File: UpstreamPacketHandler.java    From ProxyPass with GNU Affero General Public License v3.0 6 votes vote down vote up
private static boolean validateChainData(JsonNode data) throws Exception {
    ECPublicKey lastKey = null;
    boolean validChain = false;
    for (JsonNode node : data) {
        JWSObject jwt = JWSObject.parse(node.asText());

        if (!validChain) {
            validChain = verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());
        }

        if (lastKey != null) {
            verifyJwt(jwt, lastKey);
        }

        JsonNode payloadNode = ProxyPass.JSON_MAPPER.readTree(jwt.getPayload().toString());
        JsonNode ipkNode = payloadNode.get("identityPublicKey");
        Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain");
        lastKey = EncryptionUtils.generateKey(ipkNode.asText());
    }
    return validChain;
}
 
Example 4
Source File: JWT.java    From api-server-seed with Apache License 2.0 6 votes vote down vote up
public static JWTUser getJWTUser(String token) throws JWTException {
	if (StringUtils.isEmpty(token)) {
		throw new JWTException("没有找到token信息!");
	}
	try {
		JWSObject jwsObject = JWSObject.parse(token);
		if (JWT.verify(jwsObject)) {
			// 判断有效期,不在有效期内则直接抛出错误
			JWTUser user = new JWTUser(jwsObject.getPayload().toJSONObject());
			if (user.getExp() >= Calendar.getInstance().getTimeInMillis()) {
				return user;
			} else {
				throw new JWTException("token已经超过有效期!");
			}
		} else {
			throw new JWTException("token校验失败!");
		}
	} catch (Exception e) {
		throw new JWTException(e);
	}
}
 
Example 5
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static boolean verifySignature( String token, String sharedKey )
{
    boolean verifiedSignature = false;

    try
    {
        JWSObject jwsObject = JWSObject.parse( token );
        JWSVerifier verifier = new MACVerifier( sharedKey.getBytes() );
        verifiedSignature = jwsObject.verify( verifier );
    }
    catch ( Exception e )
    {
        LOG.warn( e.getMessage() );
    }

    return verifiedSignature;
}
 
Example 6
Source File: JWTOrFormAuthenticationFilter.java    From shiro-jwt with MIT License 6 votes vote down vote up
public JWTAuthenticationToken createToken(String token) {
    try {
        JWSObject jwsObject = JWSObject.parse(token);
        String decrypted = jwsObject.getPayload().toString();
        
        try (JsonReader jr = Json.createReader(new StringReader(decrypted))) {
            JsonObject object = jr.readObject();

            String userId = object.getString("sub", null);
            return new JWTAuthenticationToken(userId, token);
        }

    } catch (ParseException ex) {
        throw new AuthenticationException(ex);
    }

}
 
Example 7
Source File: LoginEncryptionUtils.java    From Geyser with MIT License 5 votes vote down vote up
private static void encryptConnectionWithCert(GeyserConnector connector, GeyserSession session, String clientData, JsonNode certChainData) {
    try {
        boolean validChain = validateChainData(certChainData);

        connector.getLogger().debug(String.format("Is player data valid? %s", validChain));

        JWSObject jwt = JWSObject.parse(certChainData.get(certChainData.size() - 1).asText());
        JsonNode payload = JSON_MAPPER.readTree(jwt.getPayload().toBytes());

        if (payload.get("extraData").getNodeType() != JsonNodeType.OBJECT) {
            throw new RuntimeException("AuthData was not found!");
        }

        JsonNode extraData = payload.get("extraData");
        session.setAuthenticationData(new AuthData(
                extraData.get("displayName").asText(),
                UUID.fromString(extraData.get("identity").asText()),
                extraData.get("XUID").asText()
        ));

        if (payload.get("identityPublicKey").getNodeType() != JsonNodeType.STRING) {
            throw new RuntimeException("Identity Public Key was not found!");
        }

        ECPublicKey identityPublicKey = EncryptionUtils.generateKey(payload.get("identityPublicKey").textValue());
        JWSObject clientJwt = JWSObject.parse(clientData);
        EncryptionUtils.verifyJwt(clientJwt, identityPublicKey);

        session.setClientData(JSON_MAPPER.convertValue(JSON_MAPPER.readTree(clientJwt.getPayload().toBytes()), BedrockClientData.class));

        if (EncryptionUtils.canUseEncryption()) {
            LoginEncryptionUtils.startEncryptionHandshake(session, identityPublicKey);
        }
    } catch (Exception ex) {
        session.disconnect("disconnectionScreen.internalError.cantConnect");
        throw new RuntimeException("Unable to complete login", ex);
    }
}
 
Example 8
Source File: EncryptionUtils.java    From Protocol with Apache License 2.0 5 votes vote down vote up
/**
 * Verify the validity of the login chain data from the {@link com.nukkitx.protocol.bedrock.packet.LoginPacket}
 *
 * @param chain array of JWS objects
 * @return chain validity
 * @throws JOSEException            invalid JWS algorithm used
 * @throws ParseException           invalid JWS object
 * @throws InvalidKeySpecException  invalid EC key provided
 * @throws NoSuchAlgorithmException runtime does not support EC spec
 */
public static boolean verifyChain(JSONArray chain) throws JOSEException, ParseException, InvalidKeySpecException, NoSuchAlgorithmException {
    ECPublicKey lastKey = null;
    boolean validChain = false;
    for (Object node : chain) {
        Preconditions.checkArgument(node instanceof String, "Chain node is not a string");
        JWSObject jwt = JWSObject.parse((String) node);

        if (lastKey == null) {
            validChain = verifyJwt(jwt, MOJANG_PUBLIC_KEY);
        } else {
            validChain = verifyJwt(jwt, lastKey);
        }

        if (!validChain) {
            break;
        }

        Object payload = JSONValue.parse(jwt.getPayload().toString());
        Preconditions.checkArgument(payload instanceof JSONObject, "Payload is not a object");

        Object identityPublicKey = ((JSONObject) payload).get("identityPublicKey");
        Preconditions.checkArgument(identityPublicKey instanceof String, "identityPublicKey node is missing in chain");
        lastKey = generateKey((String) identityPublicKey);
    }
    return validChain;
}
 
Example 9
Source File: ClientChainData.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
private boolean verifyChain(List<String> chains) throws Exception {

        PublicKey lastKey = null;
        boolean mojangKeyVerified = false;
        for (String chain: chains) {
            JWSObject jws = JWSObject.parse(chain);

            if (!mojangKeyVerified) {
                // First chain should be signed using Mojang's private key. We'd be in big trouble if it leaked...
                mojangKeyVerified = verify(MOJANG_PUBLIC_KEY, jws);
            }

            if (lastKey != null) {
                if (!verify(lastKey, jws)) {
                    throw new JOSEException("Unable to verify key in chain.");
                }
            }

            JSONObject payload = jws.getPayload().toJSONObject();
            String base64key = payload.getAsString("identityPublicKey");
            if (base64key == null) {
                throw new RuntimeException("No key found");
            }
            lastKey = generateKey(base64key);
        }
        return mojangKeyVerified;
    }
 
Example 10
Source File: TokenUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static boolean verifySignatureAndDate( String token, String sharedKey ) throws SystemSecurityException
{
    try
    {
        JWSObject jwsObject = JWSObject.parse( token );
        JWSVerifier verifier = new MACVerifier( sharedKey.getBytes() );

        if ( jwsObject.verify( verifier ) )
        {
            long date = getDate( jwsObject );

            if ( date == 0 || System.currentTimeMillis() <= date )
            {
                return true;
            }
            else
            {
                throw new IdentityExpiredException();
            }
        }
        else
        {
            throw new InvalidLoginException();
        }
    }
    catch ( JOSEException | ParseException ex )
    {
        LOG.warn( ex.getMessage() );

        throw new InvalidLoginException();
    }
}
 
Example 11
Source File: TokenUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static Payload parseToken( String token )
{
    Payload payload = null;
    try
    {
        JWSObject jwsObject = JWSObject.parse( token );
        payload = jwsObject.getPayload();
    }
    catch ( Exception e )
    {
        LOG.error( "Error parsing token", e.getMessage() );
    }

    return payload;
}
 
Example 12
Source File: Jwt.java    From JWT with MIT License 5 votes vote down vote up
/**
    * 校验token是否合法,返回Map集合,集合中主要包含    state状态码   data鉴权成功后从token中提取的数据
    * 该方法在过滤器中调用,每次请求API时都校验
    * @param token
    * @return  Map<String, Object>
    */
public static Map<String, Object> validToken(String token) {
	Map<String, Object> resultMap = new HashMap<String, Object>();
	try {
		JWSObject jwsObject = JWSObject.parse(token);
		Payload payload = jwsObject.getPayload();
		JWSVerifier verifier = new MACVerifier(SECRET);

		if (jwsObject.verify(verifier)) {
			JSONObject jsonOBj = payload.toJSONObject();
			// token校验成功(此时没有校验是否过期)
			resultMap.put("state", TokenState.VALID.toString());
			// 若payload包含ext字段,则校验是否过期
			if (jsonOBj.containsKey("ext")) {
				long extTime = Long.valueOf(jsonOBj.get("ext").toString());
				long curTime = new Date().getTime();
				// 过期了
				if (curTime > extTime) {
					resultMap.clear();
					resultMap.put("state", TokenState.EXPIRED.toString());
				}
			}
			resultMap.put("data", jsonOBj);

		} else {
			// 校验失败
			resultMap.put("state", TokenState.INVALID.toString());
		}

	} catch (Exception e) {
		//e.printStackTrace();
		// token格式不合法导致的异常
		resultMap.clear();
		resultMap.put("state", TokenState.INVALID.toString());
	}
	return resultMap;
}
 
Example 13
Source File: ClientChainData.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
private boolean verifyChain(List<String> chains) throws Exception {

        PublicKey lastKey = null;
        boolean mojangKeyVerified = false;
        for (String chain: chains) {
            JWSObject jws = JWSObject.parse(chain);

            if (!mojangKeyVerified) {
                // First chain should be signed using Mojang's private key. We'd be in big trouble if it leaked...
                mojangKeyVerified = verify(MOJANG_PUBLIC_KEY, jws);
            }

            if (lastKey != null) {
                if (!verify(lastKey, jws)) {
                    throw new JOSEException("Unable to verify key in chain.");
                }
            }

            JSONObject payload = jws.getPayload().toJSONObject();
            String base64key = payload.getAsString("identityPublicKey");
            if (base64key == null) {
                throw new RuntimeException("No key found");
            }
            lastKey = generateKey(base64key);
        }
        return mojangKeyVerified;
    }
 
Example 14
Source File: PoPAuthenticationManager.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {
    Authentication authenticationResult = authenticationManager
        .authenticate(authentication);

    if (authenticationResult.isAuthenticated()) {
        // validates nonce because JWT is already valid
        if (authentication instanceof PoPAuthenticationToken) {
            PoPAuthenticationToken popAuthentication = (PoPAuthenticationToken) authentication;

            // starts validating nonce here
            String nonce = popAuthentication.getNonce();
            if (nonce == null) {
                throw new UnapprovedClientAuthenticationException(
                    "This request does not have a valid signed nonce");
            }

            String token = (String) popAuthentication.getPrincipal();

            System.out.println("access token:" + token);

            try {
                JWT jwt = JWTParser.parse(token);
                String publicKey = jwt.getJWTClaimsSet().getClaim("public_key").toString();
                JWK jwk = JWK.parse(publicKey);

                JWSObject jwsNonce = JWSObject.parse(nonce);
                JWSVerifier verifier = new RSASSAVerifier((RSAKey) jwk);
                if (!jwsNonce.verify(verifier)) {
                    throw new InvalidTokenException("Client hasn't possession of given token");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }

    return authenticationResult;
}