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

The following examples show how to use org.apache.cxf.common.util.Base64Utility#encode() . 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: GeoFenceClient.java    From geofence with GNU General Public License v2.0 6 votes vote down vote up
protected <T>T getService(Class<T> clazz, String endpoint) {
        if(services.containsKey(clazz))
            return (T)services.get(clazz);

        if(restUrl == null)
            new IllegalStateException("GeoFence URL not set");

        synchronized(services) {
//            T proxy = JAXRSClientFactory.create(restUrl, clazz, username, password, null);
            
            T proxy = JAXRSClientFactory.create(restUrl+"/"+endpoint, clazz);
            String authorizationHeader = "Basic "  + Base64Utility.encode((username+":"+password).getBytes());
            WebClient.client(proxy).header("Authorization", authorizationHeader);

//        WebClient.client(proxy).accept("text/xml");
            services.put(clazz, proxy);
            return proxy;
        }
    }
 
Example 2
Source File: WSS4JTokenConverter.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static void convertToken(Message msg, Principal p) {
    if (p instanceof UsernameTokenPrincipal) {
        UsernameTokenPrincipal utp = (UsernameTokenPrincipal)p;
        String nonce = null;
        if (utp.getNonce() != null) {
            nonce = Base64Utility.encode(utp.getNonce());
        }
        msg.put(org.apache.cxf.common.security.SecurityToken.class,
                new UsernameToken(utp.getName(),
                                  utp.getPassword(),
                                  utp.getPasswordType(),
                                  utp.isPasswordDigest(),
                                  nonce,
                                  utp.getCreatedTime()));

    }
}
 
Example 3
Source File: HmacAuthInterceptor.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
public static String calculateSignature(String data, String key) {
    logger.debug("Signing with algorithm {} the string: {} ", HMAC_SHA1_ALGORITHM, data);
    String result;
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes());

        // base64-encode the hmac
        result = Base64Utility.encode(rawHmac);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}
 
Example 4
Source File: RESTSecurityTokenServiceImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String encodeToken(String assertion) throws Base64Exception {
    byte[] tokenBytes = assertion.getBytes(StandardCharsets.UTF_8);

    if (useDeflateEncoding) {
        tokenBytes = CompressionUtils.deflate(tokenBytes, getDeflateLevel(), true);
    }
    StringWriter writer = new StringWriter();
    Base64Utility.encode(tokenBytes, 0, tokenBytes.length, writer);
    return writer.toString();
}
 
Example 5
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 6
Source File: AbstractSamlOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String encodeToken(String assertion) throws Base64Exception {
    byte[] tokenBytes = assertion.getBytes(StandardCharsets.UTF_8);

    if (useDeflateEncoding) {
        tokenBytes = new DeflateEncoderDecoder().deflateToken(tokenBytes);
    }
    StringWriter writer = new StringWriter();
    Base64Utility.encode(tokenBytes, 0, tokenBytes.length, writer);
    return writer.toString();
}
 
Example 7
Source File: CryptoUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static String encodeCertificate(Certificate cert) {
    try {
        return Base64Utility.encode(cert.getEncoded());
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example 8
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static String encodeAuthnRequest(XMLObject request) throws WSSecurityException {
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    String requestMessage = DOM2Writer.nodeToString(OpenSAMLUtil.toDom(request, doc));

    DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
    byte[] deflatedBytes = encoder.deflateToken(requestMessage.getBytes(UTF_8));

    return Base64Utility.encode(deflatedBytes);
}
 
Example 9
Source File: JAXRSSamlTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private String encodeToken(String assertion) throws Base64Exception {
    byte[] tokenBytes = assertion.getBytes(StandardCharsets.UTF_8);

    tokenBytes = new DeflateEncoderDecoder().deflateToken(tokenBytes);
    StringWriter writer = new StringWriter();
    Base64Utility.encode(tokenBytes, 0, tokenBytes.length, writer);
    return writer.toString();
}
 
Example 10
Source File: SamlPostBindingFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String encodeAuthnRequest(Element authnRequest) throws IOException {
    String requestMessage = DOM2Writer.nodeToString(authnRequest);

    byte[] deflatedBytes = null;
    // Not correct according to the spec but required by some IDPs.
    if (useDeflateEncoding) {
        DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
        deflatedBytes = encoder.deflateToken(requestMessage.getBytes(StandardCharsets.UTF_8));
    } else {
        deflatedBytes = requestMessage.getBytes(StandardCharsets.UTF_8);
    }

    return Base64Utility.encode(deflatedBytes);
}
 
Example 11
Source File: OAuthDataProviderImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void registerCert(Client client) throws Exception {
    Certificate cert = loadCert();
    String encodedCert = Base64Utility.encode(cert.getEncoded());
    client.setApplicationCertificates(Collections.singletonList(encodedCert));

}
 
Example 12
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSuccessfulInvokeOnIdPUsingPOST() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    // Create the AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up");
    signAuthnRequest(authnRequest);

    Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);

    // Don't inflate the token...
    String requestMessage = DOM2Writer.nodeToString(authnRequestElement);
    String authnRequestEncoded = Base64Utility.encode(requestMessage.getBytes(UTF_8.name()));

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);

    WebRequest request = new WebRequest(new URL(url), HttpMethod.POST);

    request.setRequestParameters(new ArrayList<NameValuePair>());
    request.getRequestParameters().add(new NameValuePair(SSOConstants.RELAY_STATE, relayState));
    request.getRequestParameters().add(new NameValuePair(SSOConstants.SAML_REQUEST, authnRequestEncoded));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(request);

    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Success";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    // Check claims
    String parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    String claim = ClaimTypes.FIRSTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.LASTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.EMAILADDRESS.toString();
    Assert.assertTrue(parsedResponse.contains(claim));

    webClient.close();
}
 
Example 13
Source File: Client.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static String base64Encode(String value) {
    return Base64Utility.encode(value.getBytes());
}
 
Example 14
Source File: SparkUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static String getRandomId() {
    byte[] bytes = new byte[10];
    new Random().nextBytes(bytes);
    return Base64Utility.encode(bytes);
}
 
Example 15
Source File: HmacUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static String encodeHmacString(String macSecret, String macAlgoJavaName, String data, boolean urlSafe) {
    byte[] bytes = computeHmac(macSecret, macAlgoJavaName, data);
    return urlSafe ? Base64UrlUtility.encode(bytes) : Base64Utility.encode(bytes);
}
 
Example 16
Source File: DefaultBasicAuthSupplier.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static String getBasicAuthHeader(String userName, String passwd, boolean useIso8859) {
    final String userAndPass = userName + ':' + passwd;
    byte[] authBytes = useIso8859 ? userAndPass.getBytes(StandardCharsets.ISO_8859_1) : userAndPass.getBytes();
    return "Basic " + Base64Utility.encode(authBytes);
}
 
Example 17
Source File: HawkAuthorizationScheme.java    From cxf with Apache License 2.0 4 votes vote down vote up
private static String generateNonce() {
    byte[] randomBytes = new byte[20];
    new SecureRandom().nextBytes(randomBytes);
    return Base64Utility.encode(randomBytes);
}
 
Example 18
Source File: RestRequestForDiagramViewer.java    From activiti-in-action-codes with Apache License 2.0 4 votes vote down vote up
private static WebClient createClient(String uri) {
    WebClient client = WebClient.create(BASE_REST_URI + uri);
    String auth = "Basic " + Base64Utility.encode("kermit:000000".getBytes());
    client.header("Authorization", auth);
    return client;
}
 
Example 19
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testProblemWithParsingRequest() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    // Create the AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld-xyz", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
    signAuthnRequest(authnRequest);

    Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);

    // Don't inflate the token...
    String requestMessage = DOM2Writer.nodeToString(authnRequestElement);
    String authnRequestEncoded = Base64Utility.encode(requestMessage.getBytes(UTF_8));

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    try {
        webClient.getPage(url);
        Assert.fail("Failure expected on parsing the request in the IdP");
    }  catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 400);
    }

    webClient.close();
}
 
Example 20
Source File: AbstractDownloadTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
public static String encode( String uid, String password )
{
    return "Basic " + Base64Utility.encode( ( uid + ":" + password ).getBytes() );
}