Java Code Examples for org.apache.cxf.common.util.Base64Utility#decode()

The following examples show how to use org.apache.cxf.common.util.Base64Utility#decode() . 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: JWTVerifier.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Get the public key that is used to verify the JWT from the user service. We assume the key is
 * an RSA key.
 *
 * @throws NoSuchAlgorithmException
 */
private PublicKey getPublicKey()
    throws Base64Exception, InvalidKeySpecException, NoSuchAlgorithmException {
  String url =
      "https://" + libertyHostname + ":" + libertySslPort + "/jwt/ibm/api/jwtUserBuilder/jwk";
  Response response = processRequest(url, "GET", null, null);
  assertEquals(
      "HTTP response code should have been " + Status.OK.getStatusCode() + ".",
      Status.OK.getStatusCode(),
      response.getStatus());

  // Liberty returns the keys in an array.  We'll grab the first one (there
  // should only be one).
  JsonObject jwkResponse = toJsonObj(response.readEntity(String.class));
  JsonArray jwkArray = jwkResponse.getJsonArray("keys");
  JsonObject jwk = jwkArray.getJsonObject(0);
  BigInteger modulus = new BigInteger(1, Base64Utility.decode(jwk.getString("n"), true));
  BigInteger publicExponent = new BigInteger(1, Base64Utility.decode(jwk.getString("e"), true));
  return KeyFactory.getInstance("RSA")
      .generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
}
 
Example 2
Source File: CustomerMetricsInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {
    ExchangeMetrics m = message.getExchange().get(ExchangeMetrics.class);
    if (m != null) {
        Map<String, List<String>> h = CastUtils.cast((Map<?, ?>)message.get(Message.PROTOCOL_HEADERS));
        String auth = h.get("Authorization").toString();
        auth = auth.substring(auth.indexOf(' ') + 1);
        try {
            auth = new String(Base64Utility.decode(auth));
        } catch (Base64Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        auth = auth.substring(0, auth.indexOf(':'));
        Customer c = customers.get(auth);
        if (c == null) {
            throw new RuntimeException("Not authorized");
        }
        m.addContext(c.getMetricsContext(registry));
        message.getExchange().put(Customer.class, c);
    }
}
 
Example 3
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssueSAML2TokenPlain() throws Exception {
    WebClient client = webClient()
        .path("saml2.0")
        .accept(MediaType.TEXT_PLAIN);

    String encodedAssertion = client.get(String.class);
    assertNotNull(encodedAssertion);

    byte[] deflatedToken = Base64Utility.decode(encodedAssertion);
    InputStream inputStream = CompressionUtils.inflate(deflatedToken);
    Document doc =
        StaxUtils.read(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

    // Process the token
    SamlAssertionWrapper assertion = validateSAMLToken(doc);
    assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);
}
 
Example 4
Source File: AuthorizationFilter.java    From iaf with Apache License 2.0 6 votes vote down vote up
private boolean login(ContainerRequestContext requestContext) {
	String authorization = requestContext.getHeaderString("Authorization");
	String[] parts = authorization.split(" ");
	if (parts.length != 2 || !"Basic".equals(parts[0])) {
		return false;
	}

	String decodedValue = null;
	try {
		decodedValue = new String(Base64Utility.decode(parts[1]));
	} catch (Base64Exception ex) {
		return false;
	}
	String[] namePassword = decodedValue.split(":");

	try {
		request.login(namePassword[0], namePassword[1]);
	} catch (Exception e) {
		return false;
	}
	return true;
}
 
Example 5
Source File: OAuthUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static boolean compareTlsCertificates(TLSSessionInfo tlsInfo,
                                      List<String> base64EncodedCerts) {
    Certificate[] clientCerts = tlsInfo.getPeerCertificates();
    if (clientCerts.length == base64EncodedCerts.size()) {
        try {
            for (int i = 0; i < clientCerts.length; i++) {
                X509Certificate x509Cert = (X509Certificate)clientCerts[i];
                byte[] encodedKey = x509Cert.getEncoded();
                byte[] clientKey = Base64Utility.decode(base64EncodedCerts.get(i));
                if (!Arrays.equals(encodedKey, clientKey)) {
                    return false;
                }
            }
            return true;
        } catch (Exception ex) {
            // throw exception later
        }
    }
    return false;
}
 
Example 6
Source File: AuthnRequestParser.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected RequestAbstractType extractRequest(RequestContext context, String samlRequest) throws Exception {
    byte[] deflatedToken = Base64Utility.decode(samlRequest);
    String httpMethod = WebUtils.getHttpServletRequest(context).getMethod();

    InputStream tokenStream = supportDeflateEncoding || "GET".equals(httpMethod)
         ? new DeflateEncoderDecoder().inflateToken(deflatedToken)
             : new ByteArrayInputStream(deflatedToken);

    Document responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    if (LOG.isDebugEnabled()) {
        LOG.debug(DOM2Writer.nodeToString(responseDoc));
    }
    return (RequestAbstractType)OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
}
 
Example 7
Source File: JWTVerifier.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
public void validateJWT(String authHeader, PublicKey publicKey) {
  assertNotNull("Authorization header was not present in response", authHeader);
  assertTrue("Authorization header does not contain a bearer", authHeader.startsWith("Bearer "));

  StringTokenizer st = new StringTokenizer(authHeader.substring(7), ".");
  assertTrue("JWT does not contain three parts", st.countTokens() == 3);

  String jwtHeaderEnc = st.nextToken();
  String jwtClaimsEnc = st.nextToken();
  String jwtSigEnc = st.nextToken();

  try {
    // Decode the signature we got from the server
    byte[] jwtExpectedSig = Base64Utility.decode(jwtSigEnc, true);

    // Validate the signature.
    Signature sig = Signature.getInstance(JWT_ALGORITHM);
    sig.initVerify(publicKey);
    sig.update(new String(jwtHeaderEnc + "." + jwtClaimsEnc).getBytes());
    assertTrue("JWT expected and actual signatures don't match", sig.verify(jwtExpectedSig));
  } catch (Base64Exception be) {
    Assert.fail("Exception decoding JWT signature: " + be.toString());
  } catch (Throwable t) {
    System.out.println(t.toString());
    t.printStackTrace(System.out);
    Assert.fail("Exception validating JWT signature: " + t.toString());
  }
}
 
Example 8
Source File: SamlSso.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected AuthnRequest extractRequest(String samlRequest) throws Base64Exception,
    DataFormatException, XMLStreamException, IOException, WSSecurityException {
    byte[] deflatedToken = Base64Utility.decode(samlRequest);

    final Document responseDoc;
    try (InputStream tokenStream = new DeflateEncoderDecoder().inflateToken(deflatedToken)) {
        responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    }
    AuthnRequest request =
        (AuthnRequest)OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
    System.out.println(DOM2Writer.nodeToString(responseDoc));
    return request;
}
 
Example 9
Source File: ServiceListJAASAuthenticator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static String base64Decode(String srcString) {
    byte[] transformed = null;
    try {
        transformed = Base64Utility.decode(srcString);
        return new String(transformed, "ISO-8859-1");
    } catch (UnsupportedEncodingException | Base64Exception e) {
        return srcString;
    }
}
 
Example 10
Source File: DeflateEncoderDecoderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testInflateDeflateBase64() throws Exception {
    DeflateEncoderDecoder inflater = new DeflateEncoderDecoder();
    byte[] deflated = inflater.deflateToken("valid_grant".getBytes());
    String base64String = Base64Utility.encode(deflated);
    byte[] base64decoded = Base64Utility.decode(base64String);
    InputStream is = inflater.inflateToken(base64decoded);
    assertNotNull(is);
    assertEquals("valid_grant", IOUtils.readStringFromStream(is));
}
 
Example 11
Source File: AuthorizationUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static String[] getBasicAuthParts(String basicAuthData) {
    final String authDecoded;
    try {
        authDecoded = new String(Base64Utility.decode(basicAuthData));
    } catch (Exception ex) {
        throw ExceptionUtils.toNotAuthorizedException(ex, null);
    }
    String[] authInfo = authDecoded.split(":");
    if (authInfo.length == 2) {
        return authInfo;
    }
    throw ExceptionUtils.toNotAuthorizedException(null, null);
}
 
Example 12
Source File: KerberosAuthenticationFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
private byte[] getServiceTicket(String encodedServiceTicket) {
    try {
        return Base64Utility.decode(encodedServiceTicket);
    } catch (Base64Exception ex) {
        throw ExceptionUtils.toNotAuthorizedException(null, getFaultResponse());
    }
}
 
Example 13
Source File: CryptoUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Certificate decodeCertificate(String encodedCert) {
    try {
        byte[] decoded = Base64Utility.decode(encodedCert);
        return CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(decoded));
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example 14
Source File: PushBack401.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * This function extracts the user:pass token from
 * the Authorization:Basic header. It returns a two element
 * String array, the first being the userid, the second
 * being the password. It returns null, if it cannot parse.
 */
private String[] extractUserPass(String token) {
    try {
        byte[] userpass = Base64Utility.decode(token);
        String up = IOUtils.newStringFromBytes(userpass);
        String user = up.substring(0, up.indexOf(':'));
        String pass = up.substring(up.indexOf(':') + 1);
        return new String[] {user, pass};
    } catch (Exception e) {
        return null;
    }

}
 
Example 15
Source File: AbstractHawkAccessTokenValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
public AccessTokenValidation validateAccessToken(MessageContext mc,
    String authScheme, String authSchemeData, MultivaluedMap<String, String> extraProps)
    throws OAuthServiceException {

    Map<String, String> schemeParams = getSchemeParameters(authSchemeData);
    AccessTokenValidation atv =
        getAccessTokenValidation(mc, authScheme, authSchemeData, extraProps, schemeParams);
    if (isRemoteSignatureValidation()) {
        return atv;
    }

    String macKey = atv.getExtraProps().get(OAuthConstants.HAWK_TOKEN_KEY);
    String macAlgo = atv.getExtraProps().get(OAuthConstants.HAWK_TOKEN_ALGORITHM);


    final HttpRequestProperties httpProps;
    if (extraProps != null && extraProps.containsKey(HTTP_VERB) && extraProps.containsKey(HTTP_URI)) {
        httpProps = new HttpRequestProperties(URI.create(extraProps.getFirst(HTTP_URI)),
                                              extraProps.getFirst(HTTP_VERB));
    } else {
        httpProps = new HttpRequestProperties(mc.getUriInfo().getRequestUri(),
                                              mc.getHttpServletRequest().getMethod());
    }
    HawkAuthorizationScheme macAuthInfo = new HawkAuthorizationScheme(httpProps, schemeParams);
    String normalizedString = macAuthInfo.getNormalizedRequestString();
    try {
        HmacAlgorithm hmacAlgo = HmacAlgorithm.toHmacAlgorithm(macAlgo);
        byte[] serverMacData = HmacUtils.computeHmac(macKey, hmacAlgo.getJavaName(), normalizedString);

        String clientMacString = schemeParams.get(OAuthConstants.HAWK_TOKEN_SIGNATURE);
        byte[] clientMacData = Base64Utility.decode(clientMacString);
        boolean validMac = MessageDigest.isEqual(serverMacData, clientMacData);
        if (!validMac) {
            AuthorizationUtils.throwAuthorizationFailure(Collections
                .singleton(OAuthConstants.HAWK_AUTHORIZATION_SCHEME));
        }
    } catch (Base64Exception e) {
        throw new OAuthServiceException(OAuthConstants.SERVER_ERROR, e);
    }
    validateTimestampNonce(macKey, macAuthInfo.getTimestamp(), macAuthInfo.getNonce());
    return atv;
}
 
Example 16
Source File: DeflateEncoderDecoderTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test(expected = DataFormatException.class)
public void testInvalidContentAfterBase64() throws Exception {
    DeflateEncoderDecoder inflater = new DeflateEncoderDecoder();
    byte[] base64decoded = Base64Utility.decode("invalid_grant");
    inflater.inflateToken(base64decoded);
}
 
Example 17
Source File: Base64Type.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public Object readObject(MessageReader mreader, Context context) throws DatabindingException {
    XMLStreamReader reader = mreader.getXMLStreamReader();

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        reader.next();
        while (!reader.isCharacters() && !reader.isEndElement() && !reader.isStartElement()) {
            reader.next();
        }

        if (reader.isStartElement() && reader.getName().equals(AbstractXOPType.XOP_INCLUDE)) {
            return optimizedType.readMtoM(mreader, context);
        }

        if (reader.isEndElement()) {
            reader.next();
            return new byte[0];
        }

        CharArrayWriter writer = new CharArrayWriter(2048);
        while (reader.isCharacters()) {
            writer.write(reader.getTextCharacters(),
                         reader.getTextStart(),
                         reader.getTextLength());
            reader.next();
        }
        Base64Utility.decode(writer.toCharArray(), 0, writer.size(), bos);

        while (reader.getEventType() != XMLStreamConstants.END_ELEMENT) {
            reader.next();
        }

        // Advance just past the end element
        reader.next();

        return bos.toByteArray();
    } catch (Base64Exception | XMLStreamException e) {
        throw new DatabindingException("Could not parse base64Binary data.", e);
    }
}
 
Example 18
Source File: AbstractTests.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Test
public void testEntityExpansionAttack2() throws Exception {

    String url = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
    String user = "alice";
    String password = "ecila";

    // Get the initial token
    CookieManager cookieManager = new CookieManager();
    final WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Parse the form to get the token (wresult)
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    String entity = getResourceAsString("/entity2.xml");
    String reference = "&m;";

    for (DomElement result : results) {
        if (getTokenName().equals(result.getAttributeNS(null, "name"))) {
            // Now modify the Signature
            String value = result.getAttributeNS(null, "value");

            if (isWSFederation()) {
                value = entity + value;
                value = value.replace("alice", reference);
                result.setAttributeNS(null, "value", value);
            } else {
                // Decode response
                byte[] deflatedToken = Base64Utility.decode(value);
                InputStream inputStream = new ByteArrayInputStream(deflatedToken);

                Document responseDoc = StaxUtils.read(new InputStreamReader(inputStream, "UTF-8"));

                // Modify SignatureValue to include the entity
                String signatureNamespace = "http://www.w3.org/2000/09/xmldsig#";
                Node signatureValue =
                    responseDoc.getElementsByTagNameNS(signatureNamespace, "SignatureValue").item(0);
                signatureValue.setTextContent(reference + signatureValue.getTextContent());

                // Re-encode response
                String responseMessage = DOM2Writer.nodeToString(responseDoc);
                result.setAttributeNS(null, "value", Base64Utility.encode((entity + responseMessage).getBytes()));
            }
        }
    }

    // Invoke back on the RP

    final HtmlForm form = idpPage.getFormByName(getLoginFormName());
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    try {
        button.click();
        Assert.fail("Failure expected on an entity expansion attack");
    } catch (FailingHttpStatusCodeException ex) {
        // expected
        Assert.assertTrue(401 == ex.getStatusCode() || 403 == ex.getStatusCode());
    }

    webClient.close();
}
 
Example 19
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private static org.opensaml.saml.saml2.core.Response parseSAMLResponse(HtmlPage idpPage,
                                                                String relayState,
                                                                String consumerURL,
                                                                String authnRequestId
) throws Exception {
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Parse the form to get the token (SAMLResponse)
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    String samlResponse = null;
    boolean foundRelayState = false;
    for (DomElement result : results) {
        if ("SAMLResponse".equals(result.getAttributeNS(null, "name"))) {
            samlResponse = result.getAttributeNS(null, "value");
        } else if ("RelayState".equals(result.getAttributeNS(null, "name"))) {
            foundRelayState = true;
            Assert.assertEquals(result.getAttributeNS(null, "value"), relayState);
        }
    }

    Assert.assertNotNull(samlResponse);
    Assert.assertTrue(foundRelayState);

    // Check the "action"
    DomNodeList<DomElement> formResults = idpPage.getElementsByTagName("form");
    Assert.assertFalse(formResults.isEmpty());

    DomElement formResult = formResults.get(0);
    String action = formResult.getAttributeNS(null, "action");
    Assert.assertTrue(action.equals(consumerURL));

    // Decode + verify response
    byte[] deflatedToken = Base64Utility.decode(samlResponse);
    InputStream inputStream = new ByteArrayInputStream(deflatedToken);

    Document responseDoc = StaxUtils.read(new InputStreamReader(inputStream, UTF_8.name()));

    XMLObject responseObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
    Assert.assertTrue(responseObject instanceof org.opensaml.saml.saml2.core.Response);

    org.opensaml.saml.saml2.core.Response samlResponseObject =
        (org.opensaml.saml.saml2.core.Response)responseObject;
    Assert.assertTrue(authnRequestId.equals(samlResponseObject.getInResponseTo()));

    return samlResponseObject;
}
 
Example 20
Source File: TomcatPluginTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Test
public void testModifiedSignatureValue() throws Exception {

    String url = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
        + "/secure/fedservlet";
    String user = "alice";
    String password = "ecila";

    // Get the initial token
    CookieManager cookieManager = new CookieManager();
    final WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Parse the form to get the token (wresult)
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    for (DomElement result : results) {
        if (getTokenName().equals(result.getAttributeNS(null, "name"))) {
            String value = result.getAttributeNS(null, "value");

            // Decode response
            byte[] deflatedToken = Base64Utility.decode(value);
            InputStream inputStream = new ByteArrayInputStream(deflatedToken);

            Document responseDoc = StaxUtils.read(new InputStreamReader(inputStream, "UTF-8"));

            // Modify SignatureValue
            String signatureNamespace = "http://www.w3.org/2000/09/xmldsig#";
            Node signatureValue =
                responseDoc.getElementsByTagNameNS(signatureNamespace, "SignatureValue").item(0);
            signatureValue.setTextContent("H" + signatureValue.getTextContent());

            // Re-encode response
            String responseMessage = DOM2Writer.nodeToString(responseDoc);
            result.setAttributeNS(null, "value", Base64Utility.encode(responseMessage.getBytes()));
        }
    }

    // Invoke back on the RP

    final HtmlForm form = idpPage.getFormByName(getLoginFormName());
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    try {
        button.click();
        Assert.fail("Failure expected on a modified signature");
    } catch (FailingHttpStatusCodeException ex) {
        // expected
        Assert.assertTrue(401 == ex.getStatusCode() || 403 == ex.getStatusCode());
    }

    webClient.close();
}