예제 #1
0
  /**
   * This test verifies the precedence of Authorization Information. Setting authorization
   * information on the Message takes precedence over a Basic Auth Supplier with preemptive
   * UserPass, and that followed by setting it directly on the Conduit.
   */
  @Test
  public void testAuthPolicyPrecedence() throws Exception {
    Bus bus = new ExtensionManagerBus();
    EndpointInfo ei = new EndpointInfo();
    ei.setAddress("http://nowhere.com/bar/foo");
    HTTPConduit conduit = new URLConnectionHTTPConduit(bus, ei, null);
    conduit.finalizeConfig();

    conduit.getAuthorization().setUserName("Satan");
    conduit.getAuthorization().setPassword("hell");
    Message message = getNewMessage();

    // Test call
    conduit.prepare(message);

    Map<String, List<String>> headers =
        CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));

    assertNotNull("Authorization Header should exist", headers.get("Authorization"));

    assertEquals(
        "Unexpected Authorization Token",
        "Basic " + Base64Utility.encode("Satan:hell".getBytes()),
        headers.get("Authorization").get(0));

    // Setting a Basic Auth User Pass should override
    conduit.setAuthSupplier(new TestAuthSupplier());
    message = getNewMessage();

    // Test Call
    conduit.prepare(message);

    headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));
    List<String> authorization = headers.get("Authorization");
    assertNotNull("Authorization Token must be set", authorization);
    assertEquals("Wrong Authorization Token", "myauth", authorization.get(0));

    conduit.setAuthSupplier(null);
    // Setting authorization policy on the message should override
    // conduit setting
    AuthorizationPolicy authPolicy = new AuthorizationPolicy();
    authPolicy.setUserName("Hello");
    authPolicy.setPassword("world");
    authPolicy.setAuthorizationType("Basic");
    message = getNewMessage();
    message.put(AuthorizationPolicy.class, authPolicy);

    conduit.prepare(message);

    headers = CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));

    assertEquals(
        "Unexpected Authorization Token",
        "Basic " + Base64Utility.encode("Hello:world".getBytes()),
        headers.get("Authorization").get(0));
  }
예제 #2
0
  @Test
  public void testAuthPolicyFromEndpointInfo() throws Exception {
    Bus bus = new ExtensionManagerBus();
    EndpointInfo ei = new EndpointInfo();
    AuthorizationPolicy ap = new AuthorizationPolicy();
    ap.setPassword("password");
    ap.setUserName("testUser");
    ei.addExtensor(ap);
    ei.setAddress("http://nowhere.com/bar/foo");
    HTTPConduit conduit = new URLConnectionHTTPConduit(bus, ei, null);
    conduit.finalizeConfig();
    Message message = getNewMessage();

    // Test call
    conduit.prepare(message);

    Map<String, List<String>> headers =
        CastUtils.cast((Map<?, ?>) message.get(Message.PROTOCOL_HEADERS));

    assertNotNull("Authorization Header should exist", headers.get("Authorization"));

    assertEquals(
        "Unexpected Authorization Token",
        "Basic " + Base64Utility.encode("testUser:password".getBytes()),
        headers.get("Authorization").get(0));
  }
예제 #3
0
  /**
   * Cache HTTP headers in message.
   *
   * @param message the current message
   */
  protected void setHeaders(Message message) {
    Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>();
    copyRequestHeaders(message, requestHeaders);
    message.put(Message.PROTOCOL_HEADERS, requestHeaders);

    if (requestHeaders.containsKey("Authorization")) {
      List<String> authorizationLines = requestHeaders.get("Authorization");
      String credentials = authorizationLines.get(0);
      String authType = credentials.split(" ")[0];
      if ("Basic".equals(authType)) {
        String authEncoded = credentials.split(" ")[1];
        try {
          String authDecoded = new String(Base64Utility.decode(authEncoded));
          String authInfo[] = authDecoded.split(":");
          String username = (authInfo.length > 0) ? authInfo[0] : "";
          // Below line for systems that blank out password after authentication;
          // see CXF-1495 for more info
          String password = (authInfo.length > 1) ? authInfo[1] : "";
          AuthorizationPolicy policy = new AuthorizationPolicy();
          policy.setUserName(username);
          policy.setPassword(password);

          message.put(AuthorizationPolicy.class, policy);
        } catch (Base64Exception ex) {
          // ignore, we'll leave things alone.  They can try decoding it themselves
        }
      }
    }

    if (LOG.isLoggable(Level.FINE)) {
      LOG.log(Level.FINE, "Request Headers: " + requestHeaders.toString());
    }
  }
예제 #4
0
  public CommandOutput getCommandOutput(String shellId, String commandId) {
    String messageId = UUID.randomUUID().toString();
    HashMap<String, String> options = null; // new HashMap<>();

    prepareRequest(URI_ACTION_SHELL_RECEIVE, shellId, messageId, options);

    // add SOAP body
    Receive recv = new Receive();
    DesiredStreamType stream = new DesiredStreamType();
    stream.setCommandId(commandId);
    stream.getValue().add("stdout stderr");
    recv.setDesiredStream(stream);

    CommandOutput commandOutput = new CommandOutput();

    // fetch output in a loop until command finishes
    while (true) {
      ReceiveResponse response = wsmanService.receive(recv); // ws call

      for (StreamType streamItem : response.getStream()) {
        if (streamItem.getName().equals("stdout")) {
          try {
            commandOutput.std_out += Base64Utility.decode(new String(streamItem.getValue()));
          } catch (Base64Exception ex) {
            Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
          }
        } else if (streamItem.getName().equals("stderr")) {
          try {
            commandOutput.std_err += Base64Utility.decode(new String(streamItem.getValue()));
          } catch (Base64Exception ex) {
            Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
          }
        }
      }

      // quit loop when command output says 'done'
      if (response.getCommandState().getState().equals(COMMAND_STATE_DONE)) {
        commandOutput.statusCode = response.getCommandState().getExitCode().intValue();
        break;
      }
    }

    return commandOutput;
  }
예제 #5
0
  /**
   * This constructor initializes a new HTTP POST request with content type is set to
   * multipart/form-data
   *
   * @param requestURL
   * @param charset
   * @throws IOException
   */
  public ArkHTTPService(String requestURL, String authHeader) throws IOException {

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setRequestMethod(HttpMethod.GET);
    httpConn.setRequestProperty("Accept", "application/json");
    if (authHeader != null) {
      httpConn.setRequestProperty(
          "Authorization", "Basic " + Base64Utility.encode(authHeader.getBytes()));
    }
  }
예제 #6
0
  @Test
  public void testPrimitives() throws Exception {
    doTestType("testInt", "24", "In:24");
    doTestType("testInteger", "24", "In:24");

    doTestType("testFloat", "3.14", "In:3.14");
    doTestType("testFloatPrim", "3.14", "In:3.14");

    doTestType("testBoolean", "false", "In:false");
    doTestType("testBooleanPrim", "true", "In:true");

    doTestType("testBase64Binary", Base64Utility.encode("HelloWorld".getBytes()), "In:HelloWorld");
  }
  public void handleMessage(Message message) throws Fault {
    SecurityContext context = message.get(SecurityContext.class);
    if (context == null) {
      return;
    }
    Principal principal = context.getUserPrincipal();
    UsernameToken usernameToken = (UsernameToken) message.get(SecurityToken.class);
    if (principal == null
        || usernameToken == null
        || !principal.getName().equals(usernameToken.getName())) {
      return;
    }

    // Read the user from Syncope and get the roles
    WebClient client =
        WebClient.create(address, Collections.singletonList(new JacksonJsonProvider()));

    String authorizationHeader =
        "Basic "
            + Base64Utility.encode(
                (usernameToken.getName() + ":" + usernameToken.getPassword()).getBytes());

    client.header("Authorization", authorizationHeader);

    client = client.path("users/self");
    UserTO user = null;
    try {
      user = client.get(UserTO.class);
      if (user == null) {
        Exception exception = new Exception("Authentication failed");
        throw new Fault(exception);
      }
    } catch (RuntimeException ex) {
      if (log.isDebugEnabled()) {
        log.debug(ex.getMessage(), ex);
      }
      throw new Fault(ex);
    }

    // Now get the roles
    List<MembershipTO> membershipList = user.getMemberships();
    Subject subject = new Subject();
    subject.getPrincipals().add(principal);
    for (MembershipTO membership : membershipList) {
      String roleName = membership.getRoleName();
      subject.getPrincipals().add(new SimpleGroup(roleName, usernameToken.getName()));
    }
    subject.setReadOnly();

    message.put(SecurityContext.class, new DefaultSecurityContext(principal, subject));
  }
예제 #8
0
  /**
   * This constructor initializes a new HTTP POST request with content type is set to
   * multipart/form-data
   *
   * @param requestURL
   * @param charset
   * @throws IOException
   */
  public ArkHTTPService(String requestURL, String charset, String authHeader, String method)
      throws IOException {

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);

    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    httpConn.setRequestMethod(method);

    if (authHeader != null) {
      httpConn.setRequestProperty(
          "Authorization", "Basic " + Base64Utility.encode(authHeader.getBytes()));
    }
    httpConn.setRequestProperty("Accept", "application/json");
    httpConn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
  }
 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);
   }
 }