Search code examples
apache-camelapache-karaf

How to set basic authentication with apache camel and http4


I'm trying to use Apache Camel's Http4 component to connect to a HTTP URL that needs Basic authentication. I'm setting credentials from a camel processor through Exchange.HTTP_QUERY header. I configure my route like this:

<?xml version="1.0" encoding="UTF-8"?>
<blueprint ...>

<bean id="myProcessor"
    class="com.myCompany.Bean"
    factory-method="myProcessorBean">
</bean>

<camelContext id="myContext" xmlns="http://camel.apache.org/schema/blueprint">
    
    <route id="myRoute>
        <from uri="activemq:queue:myQueue" />
        <process ref="myProcessor" />
        <to uri="http4://oldhost"/>
    </route>
        
</camelContext>

</blueprint>

and my processor looks like:

public void process(Exchange exchange) throws Exception {
  String user = getUserFromDB();
  String pwd = getPasswordFromDB();

  String queryParameters = "authMethod=Basic&authPassword="+pwd+"authUsername="+user;
  exchange.getIn().setHeader(Exchange.HTTP_QUERY, queryParameters);
  exchange.getIn().setHeader(Exchange.HTTP_URI, "api.abc_company.com/service/to/consume");
  ....
}

It results in:

Error myContext: org.apache.camel.http.common.HttpOperationFailedException: HTTP operation failed invoking https://api.abc_company.com/service/to/consume?authMethod=Basic&authPassword=xxxxxx&authUsername=test with statusCode: 401

It seems that password was changed to xxxxxx but I'm not sure.

When I try hardcoding user and password in the URI it works well, however I need a way to set these values programmatically due to user and password are stored it the DB.


Solution

  • "authMethod=Basic&authPassword="+pwd+"authUsername="+user;

    You'll need to at & between each uri parameter. You're missing one after password.

    Try:

    String queryParameters = "authMethod=Basic&authPassword="+pwd+"&authUsername="+user;
    

    Also you should define credentials in producer endpoint URI http4://oldhost?authMethod=Basic&authPassword="+pwd+"&authUsername="+user instead of header: Exchange.HTTP_QUERY.

    If you want to do this in your processor you can try to set Authorization header manually with value basic <credentials> where <credentials> is base64 encoded username:password.

    Failed invoking https://api.abc_company.com/service/to/consume?

    If you want to connect to https site use https4://