org.apache.axiom.util.base64.Base64Utils Java Examples

The following examples show how to use org.apache.axiom.util.base64.Base64Utils. 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: MicroIntegratorBaseUtils.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * This is a utility method which can be used to set security headers in a service client. This method
 * will create authorization header according to basic security protocol. i.e. encodeBase64(username:password)
 * and put it in a HTTP header with name "Authorization".
 *
 * @param userName      User calling the service.
 * @param password      Password of the user.
 * @param rememberMe    <code>true</code> if UI asks to persist remember me cookie.
 * @param serviceClient The service client used in the communication.
 */
public static void setBasicAccessSecurityHeaders(String userName, String password, boolean rememberMe,
                                                 ServiceClient serviceClient) {

    String userNamePassword = userName + ":" + password;
    String encodedString = Base64Utils.encode(userNamePassword.getBytes());

    String authorizationHeader = "Basic " + encodedString;

    List<Header> headers = new ArrayList<Header>();

    Header authHeader = new Header("Authorization", authorizationHeader);
    headers.add(authHeader);

    if (rememberMe) {
        Header rememberMeHeader = new Header("RememberMe", TRUE);
        headers.add(rememberMeHeader);
    }

    serviceClient.getOptions().setProperty(HTTPConstants.HTTP_HEADERS, headers);
}
 
Example #2
Source File: IdentityApplicationManagementUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param key
 * @param value
 * @return
 * @throws SignatureException
 */
public static String calculateHmacSha1(String key, String value) throws SignatureException {
    String result;
    try {
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(value.getBytes());
        result = Base64Utils.encode(rawHmac);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to create the HMAC Signature", e);
        }
        throw new SignatureException("Failed to calculate HMAC : " + e.getMessage());
    }
    return result;
}
 
Example #3
Source File: SignedJWTAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private String decodeAuthorizationHeader(String authorizationHeader) {
    String[] splitValues = authorizationHeader.trim().split(" ");
    byte[] decodedBytes = Base64Utils.decode(splitValues[1].trim());
    if (decodedBytes != null) {
        return new String(decodedBytes);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Error decoding authorization header.");
        }
        return null;
    }
}
 
Example #4
Source File: EndpointUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts the username and password info from the HTTP Authorization Header
 *
 * @param authorizationHeader "Basic " + base64encode(username + ":" + password)
 * @return String array with client id and client secret.
 * @throws org.wso2.carbon.identity.base.IdentityException If the decoded data is null.
 */
public static String[] extractCredentialsFromAuthzHeader(String authorizationHeader)
        throws OAuthClientException {
    String[] splitValues = authorizationHeader.trim().split(" ");
    if(splitValues.length == 2) {
        byte[] decodedBytes = Base64Utils.decode(splitValues[1].trim());
        if (decodedBytes != null) {
            String userNamePassword = new String(decodedBytes, Charsets.UTF_8);
            return userNamePassword.split(":");
        }
    }
    String errMsg = "Error decoding authorization header. Space delimited \"<authMethod> <base64Hash>\" format violated.";
    throw new OAuthClientException(errMsg);
}
 
Example #5
Source File: SignedJWTAuthenticator.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
private String decodeAuthorizationHeader(String authorizationHeader) {
    String[] splitValues = authorizationHeader.trim().split(" ");
    byte[] decodedBytes = Base64Utils.decode(splitValues[1].trim());
    if (decodedBytes != null) {
        return new String(decodedBytes);
    } else {
        log.debug(
                "Error decoding authorization header. Could not retrieve user name and password.");
        return null;
    }
}
 
Example #6
Source File: IdentityApplicationManagementUtil.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * @param jsonObj
 * @return Base64 encoded JWT
 */
public static String getSignedJWT(String jsonObj, ServiceProvider serviceProvider) {

    String oauthConsumerSecret = null;

    if (serviceProvider.getInboundAuthenticationConfig() != null
            && serviceProvider.getInboundAuthenticationConfig()
            .getInboundAuthenticationRequestConfigs() != null
            && serviceProvider.getInboundAuthenticationConfig()
            .getInboundAuthenticationRequestConfigs().length > 0) {

        InboundAuthenticationRequestConfig[] authReqConfigs = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        for (InboundAuthenticationRequestConfig authReqConfig : authReqConfigs) {
            if ((IdentityApplicationConstants.OAuth2.NAME).equals(authReqConfig.getInboundAuthType())) {
                if (authReqConfig.getProperties() != null) {
                    for (Property property : authReqConfig.getProperties()) {
                        if ((IdentityApplicationConstants.OAuth2.OAUTH_CONSUMER_SECRET)
                                .equalsIgnoreCase(property.getName())) {
                            oauthConsumerSecret = property.getValue();
                            break;
                        }
                    }
                }
            }
        }

    }

    String jwtBody = "{\"iss\":\"wso2\",\"exp\":" + new Date().getTime() + 3000 + ",\"iat\":"
            + new Date().getTime() + "," + jsonObj + "}";
    String jwtHeader = "{\"typ\":\"JWT\", \"alg\":\"HS256\"}";

    if (oauthConsumerSecret == null) {
        jwtHeader = "{\"typ\":\"JWT\", \"alg\":\"none\"}";
    }

    String base64EncodedHeader = Base64Utils.encode(jwtHeader.getBytes(StandardCharsets.UTF_8));
    String base64EncodedBody = Base64Utils.encode(jwtBody.getBytes(StandardCharsets.UTF_8));

    if (log.isDebugEnabled()) {
        log.debug("JWT Header :" + jwtHeader);
        log.debug("JWT Body :" + jwtBody);
    }

    String assertion = base64EncodedHeader + "." + base64EncodedBody;

    if (oauthConsumerSecret == null) {
        return assertion + ".";
    } else {
        String signedAssertion;
        try {
            signedAssertion = calculateHmacSha1(oauthConsumerSecret, assertion);
            return assertion + "." + signedAssertion;
        } catch (SignatureException e) {
            log.error("Error while signing the assertion", e);
            return assertion + ".";
        }
    }
}
 
Example #7
Source File: IdentityApplicationManagementUtil.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * @param jsonObj
 * @return Base64 encoded JWT
 */
public static String getSignedJWT(String jsonObj, ServiceProvider serviceProvider) {

    String oauthConsumerSecret = null;

    if (serviceProvider.getInboundAuthenticationConfig() != null
            && serviceProvider.getInboundAuthenticationConfig()
            .getInboundAuthenticationRequestConfigs() != null
            && serviceProvider.getInboundAuthenticationConfig()
            .getInboundAuthenticationRequestConfigs().length > 0) {

        InboundAuthenticationRequestConfig[] authReqConfigs = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        for (InboundAuthenticationRequestConfig authReqConfig : authReqConfigs) {
            if ((IdentityApplicationConstants.OAuth2.NAME).equals(authReqConfig.getInboundAuthType())) {
                if (authReqConfig.getProperties() != null) {
                    for (Property property : authReqConfig.getProperties()) {
                        if ((IdentityApplicationConstants.OAuth2.OAUTH_CONSUMER_SECRET)
                                .equalsIgnoreCase(property.getName())) {
                            oauthConsumerSecret = property.getValue();
                            break;
                        }
                    }
                }
            }
        }

    }

    String jwtBody = "{\"iss\":\"wso2\",\"exp\":" + new Date().getTime() + 3000 + ",\"iat\":"
            + new Date().getTime() + "," + jsonObj + "}";
    String jwtHeader = "{\"typ\":\"JWT\", \"alg\":\"HS256\"}";

    if (oauthConsumerSecret == null) {
        jwtHeader = "{\"typ\":\"JWT\", \"alg\":\"none\"}";
    }

    String base64EncodedHeader = Base64Utils.encode(jwtHeader.getBytes());
    String base64EncodedBody = Base64Utils.encode(jwtBody.getBytes());

    if (log.isDebugEnabled()) {
        log.debug("JWT Header :" + jwtHeader);
        log.debug("JWT Body :" + jwtBody);
    }

    String assertion = base64EncodedHeader + "." + base64EncodedBody;

    if (oauthConsumerSecret == null) {
        return assertion + ".";
    } else {
        String signedAssertion;
        try {
            signedAssertion = calculateHmacSha1(oauthConsumerSecret, assertion);
            return assertion + "." + signedAssertion;
        } catch (SignatureException e) {
            log.error("Error while siging the assertion", e);
            return assertion + ".";
        }
    }
}
 
Example #8
Source File: EntitlementCacheUpdateServlet.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private void doAuthentication(HttpServletRequest req, HttpServletResponse resp) throws EntitlementCacheUpdateServletException {
    String username = req.getParameter(USERNAME_STRING);
    String password = req.getParameter(PSWD_STRING);
    String remoteIp = req.getServerName();

    if (authenticate(username, password, remoteIp)) {

        RequestDispatcher requestDispatcher = req.getRequestDispatcher(UPDATE_CACHE);
        String subjectScope = EntitlementCacheUpdateServletDataHolder.getInstance().getServletConfig().getServletContext()
                .getInitParameter(SUBJECT_SCOPE);
        String subjectAttributeName = EntitlementCacheUpdateServletDataHolder.getInstance().getServletConfig().getServletContext()
                .getInitParameter("subjectAttributeName");

        if (subjectScope.equals(EntitlementConstants.REQUEST_PARAM)) {

            requestDispatcher = req.getRequestDispatcher(UPDATE_CACHE + "?" + subjectAttributeName + "=" + username);

        } else if (subjectScope.equals(EntitlementConstants.REQUEST_ATTIBUTE)) {

            req.setAttribute(subjectAttributeName, username);

        } else if (subjectScope.equals(EntitlementConstants.SESSION)) {

            req.getSession().setAttribute(subjectAttributeName, username);

        } else {

            resp.setHeader("Authorization", Base64Utils.encode((username + ":" + password).getBytes(Charset.forName("UTF-8"))));
        }

        try {
            requestDispatcher.forward(req, resp);
        } catch (Exception e) {
            log.error("Error occurred while dispatching request to /updateCacheAuth.do", e);
            throw new EntitlementCacheUpdateServletException("Error occurred while dispatching request to /updateCacheAuth.do", e);
        }

    } else {
        showAuthPage(req, resp);
    }
}
 
Example #9
Source File: TokenGenTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testAbstractJWTGenerator() throws Exception {
    JWTGenerator jwtGen = new JWTGenerator() {
        @Override
        protected Map<String, String> convertClaimMap(Map<ClaimMapping, String> userAttributes, String username) {
            return new HashMap<>();
        }
    };
    APIKeyValidationInfoDTO dto=new APIKeyValidationInfoDTO();

    TokenValidationContext validationContext = new TokenValidationContext();
    validationContext.setValidationInfoDTO(dto);
    validationContext.setContext("testAPI");
    validationContext.setVersion("1.5.0");
    validationContext.setAccessToken("DUMMY_TOKEN_STRING");

    dto.setSubscriber("sanjeewa");
    dto.setApplicationName("sanjeewa-app");
    dto.setApplicationId("1");
    dto.setApplicationTier("UNLIMITED");
    dto.setEndUserName("malalgoda");
    dto.setSubscriberTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
    //Here we will call generate token method with 4 argument.
    String token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    String header = token.split("\\.")[0];
    String decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: "+decodedHeader);
    String body = token.split("\\.")[1];
    String decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);
    // With end user name not included
    token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    header = token.split("\\.")[0];
    decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: "+decodedHeader);
    body = token.split("\\.")[1];
    decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);
    dto.setUserType(APIConstants.SUBSCRIPTION_USER_TYPE);
    token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    header = token.split("\\.")[0];
    decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: "+decodedHeader);
    body = token.split("\\.")[1];
    decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);

    token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    header = token.split("\\.")[0];
    decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: "+decodedHeader);
    body = token.split("\\.")[1];
    decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);
}
 
Example #10
Source File: TokenGenTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testJWTGeneration() throws Exception {
    JWTGenerator jwtGen = new JWTGenerator() {
        @Override
        public Map<String, String> convertClaimMap(Map<ClaimMapping, String> userAttributes, String username) {
            return new HashMap<>();
        }
    };
    APIKeyValidationInfoDTO dto=new APIKeyValidationInfoDTO();
    dto.setSubscriber("sastry");
    dto.setApplicationName("hubapp");
    dto.setApplicationId("1");
    dto.setApplicationTier("UNLIMITED");
    dto.setEndUserName("denis");
    dto.setSubscriberTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
    TokenValidationContext validationContext = new TokenValidationContext();
    validationContext.setValidationInfoDTO(dto);
    validationContext.setContext("cricScore");
    validationContext.setVersion("1.9.0");
    String token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    String header = token.split("\\.")[0];
    String decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: "+decodedHeader);
    String body = token.split("\\.")[1];
    String decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);


    // With end user name not included
    token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    header = token.split("\\.")[0];
    decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: "+decodedHeader);
    body = token.split("\\.")[1];
    decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);


    dto.setUserType(APIConstants.SUBSCRIPTION_USER_TYPE);
    token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    header = token.split("\\.")[0];
    decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: "+decodedHeader);
    body = token.split("\\.")[1];
    decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);

    token = jwtGen.generateToken(validationContext);
    System.out.println("Generated Token: " + token);
    header = token.split("\\.")[0];
    decodedHeader = new String(Base64Utils.decode(header));
    System.out.println("Header: "+decodedHeader);
    body = token.split("\\.")[1];
    decodedBody = new String(Base64Utils.decode(body));
    System.out.println("Body: " + decodedBody);


    //we can not do assert eaquals because body includes expiration time.

    /*String expectedHeader = "{\"typ\":\"JWT\"}";
    String expectedBody = "{\"iss\":\"wso2.org/products/am\", \"exp\":1349270811075, " +
                          "\"http://wso2.org/claims/subscriber\":\"sastry\", " +
                          "\"http://wso2.org/claims/applicationname\":\"hubapp\", " +
                          "\"http://wso2.org/claims/apicontext\":\"cricScore\", " +
                          "\"http://wso2.org/claims/version\":\"1.9.0\", " +
                          "\"http://wso2.org/claims/tier\":\"Bronze\", " +
                          "\"http://wso2.org/claims/enduser\":\"denis\"}";

    Assert.assertEquals(expectedHeader, decodedHeader);
    Assert.assertEquals(expectedBody, decodedBody);*/
    //String decodedToken = new String(Base64Utils.decode(token));
    //log.info(decodedToken);
    //assertNotNull(decodedToken);


}
 
Example #11
Source File: XMLTranscriptionInput.java    From cougar with Apache License 2.0 4 votes vote down vote up
private Object readObject(ParameterType paramType, OMElement node, boolean client) throws Exception {
    switch (paramType.getType()) {
        case BOOLEAN:
        case DOUBLE:
        case FLOAT:
        case INT:
        case LONG:
        case STRING:
        case ENUM:
        case DATE:
        case BYTE:
            return node == null ? null : readSimpleObject(paramType, node.getLocalName(), node.getText(), client);
        case OBJECT:
            //descend - note possibly two levels if inside a collection recursion
            OMElement _copy = this.currentNode;
            currentNode = node;

            Transcribable t = (Transcribable)paramType.getImplementationClass().newInstance();
            t.transcribe(this, TranscribableParams.getAll(), client);

            //ascend
            this.currentNode = _copy;
            return t;
        case MAP:
            Map map = new HashMap();
            for (Iterator i = node.getChildElements(); i.hasNext();) {
                OMElement element = (OMElement)i.next();
                Object key = readSimpleObject(paramType.getComponentTypes()[0],  node.getLocalName(), element.getAttributeValue(keyAttName), client);
                map.put(key, readObject(paramType.getComponentTypes()[1], (OMElement)element.getChildElements().next(), client));
            }
            return map;
        case LIST:
            if (paramType.getComponentTypes()[0].getType() == ParameterType.Type.BYTE) {
                try {
                    return Base64Utils.decode(node.getText());
                } catch (Exception e) {
                    String message = "Unable to parse " + node.getText() + " as type " + paramType;
                    LOGGER.debug(message, e);
                    throw CougarMarshallingException.unmarshallingException("soap",message,e,client);
                }
            } else {
                List list = new ArrayList();
                for (Iterator i = node.getChildElements(); i.hasNext();) {
                    list.add(readObject(paramType.getComponentTypes()[0], (OMElement)i.next(),client));
                }
                return list;
            }
        case SET:
            Set set = new HashSet();
            for (Iterator i = node.getChildElements(); i.hasNext();) {
                set.add(readObject(paramType.getComponentTypes()[0], (OMElement)i.next(),client));
            }
            return set;
    }
    return null;
}