Skip to main content

How do I use custom authentication with spark?

When using an authentication strategy that's been developed for your site, you can use the same authenticator that you use for your Java client.

If the AMPS default authenticator works with your custom authentication strategy, you simply need to provide a username and password to the server parameter, as described in the AMPS User Guide

> spark sow -topic demo -server user:pass@localhost:9007 -topic myTopic

If you have developed a custom authenticator, then you can implement the AuthenticatorFactory interface.

The AuthenticatorFactory is provided in the amps_spark.jar in the bin/lib directory of the AMPS distribution. The factory has the following interface:


package com.crankuptheamps.spark;

public interface AuthenticatorFactory {
public Authenticator createAuthenticator(String connectionURI)
throws AuthenticationException;
}

For example, a minimum implementation that just logs that the factory is called and returns the default authenticator might look like the following:

package com.crankuptheamps.examples.sparkauth;

import com.crankuptheamps.spark.AuthenticatorFactory;
import com.crankuptheamps.client.Authenticator;
import com.crankuptheamps.client.DefaultAuthenticator;
import com.crankuptheamps.client.exception.AuthenticationException;


public class MyAuthenticatorFactory implements AuthenticatorFactory
{
public MyAuthenticatorFactory() {}

public Authenticator createAuthenticator(String connectionURI) throws AuthenticationException
{
System.out.println("In new factory: returning default authenticator");
return new DefaultAuthenticator();
}

}

Once you have implemented the interface to return your custom authenticator, you can then direct spark to use your AuthenticatorFactory .

For example, if your authenticator factory is com.example.MyAuth, the command line would be:

> spark sow -topic demo -server localhost:9007 -topic myTopic \

   –authenticator com.example.MyAuth

If your custom authenticator is not found, you may need to explicitly specify the classpaths for spark to use. For example:

java -Xmx10240m -Xms10240m \
-cp ${AMPS_HOME_DIRECTORY}/bin/lib/amps_spark.jar:${AUTHENTICATOR_DIR}/myAuth.jar \
com.crankuptheamps.spark.Spark \
sow \
-authenticator com.example.myAuth \
-server localhost:9007 -type json -topic myTopic

Often, if custom authentication is required for a site, that site will modify the provided spark script or create a variation of the provided spark script to provide the correct authentication rather than requiring the full command line each time.