예제 #1
0
/** Some unit tests for the validate operation to validate X.509 tokens. */
public class ValidateX509TokenUnitTest extends org.junit.Assert {

  public static final QName REQUESTED_SECURITY_TOKEN =
      QNameConstants.WS_TRUST_FACTORY.createRequestedSecurityToken(null).getName();
  private static final QName QNAME_WST_STATUS =
      QNameConstants.WS_TRUST_FACTORY.createStatus(null).getName();

  /** Test to successfully validate an X.509 token */
  @org.junit.Test
  public void testValidateX509Token() throws Exception {
    TokenValidateOperation validateOperation = new TokenValidateOperation();

    // Add Token Validator
    List<TokenValidator> validatorList = new ArrayList<TokenValidator>();
    validatorList.add(new X509TokenValidator());
    validateOperation.setTokenValidators(validatorList);

    // Add STSProperties object
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    validateOperation.setStsProperties(stsProperties);

    // Mock up a request
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    JAXBElement<String> tokenType =
        new JAXBElement<String>(QNameConstants.TOKEN_TYPE, String.class, STSConstants.STATUS);
    request.getAny().add(tokenType);

    // Create a BinarySecurityToken
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("myclientkey");
    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    assertTrue(certs != null && certs.length > 0);

    JAXBElement<BinarySecurityTokenType> binarySecurityTokenType =
        createBinarySecurityToken(certs[0]);
    ValidateTargetType validateTarget = new ValidateTargetType();
    validateTarget.setAny(binarySecurityTokenType);

    JAXBElement<ValidateTargetType> validateTargetType =
        new JAXBElement<ValidateTargetType>(
            QNameConstants.VALIDATE_TARGET, ValidateTargetType.class, validateTarget);
    request.getAny().add(validateTargetType);

    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    Principal principal = new CustomTokenPrincipal("alice");
    msgCtx.put(SecurityContext.class.getName(), createSecurityContext(principal));

    // Validate a token
    RequestSecurityTokenResponseType response =
        validateOperation.validate(request, principal, msgCtx);
    assertTrue(validateResponse(response));
  }

  /** Test to validate an invalid X.509 token */
  @org.junit.Test
  public void testValidateInvalidX509Token() throws Exception {
    TokenValidateOperation validateOperation = new TokenValidateOperation();

    // Add Token Validator
    List<TokenValidator> validatorList = new ArrayList<TokenValidator>();
    validatorList.add(new X509TokenValidator());
    validateOperation.setTokenValidators(validatorList);

    // Add STSProperties object
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    validateOperation.setStsProperties(stsProperties);

    // Mock up a request
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    JAXBElement<String> tokenType =
        new JAXBElement<String>(QNameConstants.TOKEN_TYPE, String.class, STSConstants.STATUS);
    request.getAny().add(tokenType);

    // Create a BinarySecurityToken
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("eve");
    Crypto eveCrypto = CryptoFactory.getInstance(getEveCryptoProperties());
    X509Certificate[] certs = eveCrypto.getX509Certificates(cryptoType);
    assertTrue(certs != null && certs.length > 0);

    JAXBElement<BinarySecurityTokenType> binarySecurityTokenType =
        createBinarySecurityToken(certs[0]);
    ValidateTargetType validateTarget = new ValidateTargetType();
    validateTarget.setAny(binarySecurityTokenType);

    JAXBElement<ValidateTargetType> validateTargetType =
        new JAXBElement<ValidateTargetType>(
            QNameConstants.VALIDATE_TARGET, ValidateTargetType.class, validateTarget);
    request.getAny().add(validateTargetType);

    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    Principal principal = new CustomTokenPrincipal("alice");
    msgCtx.put(SecurityContext.class.getName(), createSecurityContext(principal));

    // Validate a token
    RequestSecurityTokenResponseType response =
        validateOperation.validate(request, principal, msgCtx);
    assertFalse(validateResponse(response));
  }

  /*
   * Create a security context object
   */
  private SecurityContext createSecurityContext(final Principal p) {
    return new SecurityContext() {
      public Principal getUserPrincipal() {
        return p;
      }

      public boolean isUserInRole(String role) {
        return false;
      }
    };
  }

  /** Return true if the response has a valid status, false otherwise */
  private boolean validateResponse(RequestSecurityTokenResponseType response) {
    assertTrue(response != null && response.getAny() != null && !response.getAny().isEmpty());

    for (Object requestObject : response.getAny()) {
      if (requestObject instanceof JAXBElement<?>) {
        JAXBElement<?> jaxbElement = (JAXBElement<?>) requestObject;
        if (QNAME_WST_STATUS.equals(jaxbElement.getName())) {
          StatusType status = (StatusType) jaxbElement.getValue();
          if (STSConstants.VALID_CODE.equals(status.getCode())) {
            return true;
          }
        }
      }
    }
    return false;
  }

  private Properties getEncryptionProperties() {
    Properties properties = new Properties();
    properties.put("org.apache.wss4j.crypto.provider", "org.apache.wss4j.common.crypto.Merlin");
    properties.put("org.apache.wss4j.crypto.merlin.keystore.password", "stsspass");
    properties.put("org.apache.wss4j.crypto.merlin.keystore.file", "stsstore.jks");

    return properties;
  }

  private Properties getEveCryptoProperties() {
    Properties properties = new Properties();
    properties.put("org.apache.wss4j.crypto.provider", "org.apache.wss4j.common.crypto.Merlin");
    properties.put("org.apache.wss4j.crypto.merlin.keystore.password", "evespass");
    properties.put("org.apache.wss4j.crypto.merlin.keystore.file", "eve.jks");

    return properties;
  }

  private JAXBElement<BinarySecurityTokenType> createBinarySecurityToken(X509Certificate cert)
      throws Exception {
    BinarySecurityTokenType binarySecurityToken = new BinarySecurityTokenType();
    binarySecurityToken.setValue(Base64.getMimeEncoder().encodeToString(cert.getEncoded()));
    binarySecurityToken.setValueType(X509TokenValidator.X509_V3_TYPE);
    binarySecurityToken.setEncodingType(WSConstants.SOAPMESSAGE_NS + "#Base64Binary");
    JAXBElement<BinarySecurityTokenType> tokenType =
        new JAXBElement<BinarySecurityTokenType>(
            QNameConstants.BINARY_SECURITY_TOKEN,
            BinarySecurityTokenType.class,
            binarySecurityToken);

    return tokenType;
  }
}
예제 #2
0
/** Some unit tests for the issue operation to issue JWT Tokens. */
public class IssueJWTUnitTest extends org.junit.Assert {

  public static final QName REQUESTED_SECURITY_TOKEN =
      QNameConstants.WS_TRUST_FACTORY.createRequestedSecurityToken(null).getName();
  public static final QName ATTACHED_REFERENCE =
      QNameConstants.WS_TRUST_FACTORY.createRequestedAttachedReference(null).getName();
  public static final QName UNATTACHED_REFERENCE =
      QNameConstants.WS_TRUST_FACTORY.createRequestedUnattachedReference(null).getName();

  private static TokenStore tokenStore = new DefaultInMemoryTokenStore();

  /** Test to successfully issue a JWT Token */
  @org.junit.Test
  public void testIssueJWTToken() throws Exception {
    TokenIssueOperation issueOperation = new TokenIssueOperation();
    issueOperation.setTokenStore(tokenStore);

    // Add Token Provider
    List<TokenProvider> providerList = new ArrayList<TokenProvider>();
    providerList.add(new JWTTokenProvider());
    issueOperation.setTokenProviders(providerList);

    // Add Service
    ServiceMBean service = new StaticService();
    service.setEndpoints(Collections.singletonList("http://dummy-service.com/dummy"));
    issueOperation.setServices(Collections.singletonList(service));

    // Add STSProperties object
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    issueOperation.setStsProperties(stsProperties);

    // Mock up a request
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    JAXBElement<String> tokenType =
        new JAXBElement<String>(
            QNameConstants.TOKEN_TYPE, String.class, JWTTokenProvider.JWT_TOKEN_TYPE);
    request.getAny().add(tokenType);
    request.getAny().add(createAppliesToElement("http://dummy-service.com/dummy"));

    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    msgCtx.put(
        SecurityContext.class.getName(), createSecurityContext(new CustomTokenPrincipal("alice")));
    WebServiceContextImpl webServiceContext = new WebServiceContextImpl(msgCtx);

    // Issue a token
    RequestSecurityTokenResponseCollectionType response =
        issueOperation.issue(request, webServiceContext);
    List<RequestSecurityTokenResponseType> securityTokenResponse =
        response.getRequestSecurityTokenResponse();
    assertTrue(!securityTokenResponse.isEmpty());

    // Test the generated token.
    String jwtToken = null;
    for (Object tokenObject : securityTokenResponse.get(0).getAny()) {
      if (tokenObject instanceof Element
          && REQUESTED_SECURITY_TOKEN.getLocalPart().equals(((Element) tokenObject).getLocalName())
          && REQUESTED_SECURITY_TOKEN
              .getNamespaceURI()
              .equals(((Element) tokenObject).getNamespaceURI())) {
        jwtToken = ((Element) tokenObject).getTextContent();
        break;
      }
    }

    assertNotNull(jwtToken);

    // Validate the token
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(jwtToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
  }

  /*
   * Create a security context object
   */
  private SecurityContext createSecurityContext(final Principal p) {
    return new SecurityContext() {
      public Principal getUserPrincipal() {
        return p;
      }

      public boolean isUserInRole(String role) {
        return false;
      }
    };
  }

  /*
   * Mock up an AppliesTo element using the supplied address
   */
  private Element createAppliesToElement(String addressUrl) {
    Document doc = DOMUtils.createDocument();
    Element appliesTo = doc.createElementNS(STSConstants.WSP_NS, "wsp:AppliesTo");
    appliesTo.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsp", STSConstants.WSP_NS);
    Element endpointRef = doc.createElementNS(STSConstants.WSA_NS_05, "wsa:EndpointReference");
    endpointRef.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsa", STSConstants.WSA_NS_05);
    Element address = doc.createElementNS(STSConstants.WSA_NS_05, "wsa:Address");
    address.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsa", STSConstants.WSA_NS_05);
    address.setTextContent(addressUrl);
    endpointRef.appendChild(address);
    appliesTo.appendChild(endpointRef);
    return appliesTo;
  }

  private Properties getEncryptionProperties() {
    Properties properties = new Properties();
    properties.put("org.apache.wss4j.crypto.provider", "org.apache.wss4j.common.crypto.Merlin");
    properties.put("org.apache.wss4j.crypto.merlin.keystore.password", "stsspass");
    properties.put("org.apache.wss4j.crypto.merlin.keystore.file", "stsstore.jks");

    return properties;
  }
}