Service Client

Create an Service Client

A service client can be created by using the client factory. It uses service-specific data to identify itself, sign the request data, and decrypt encrypted response data. All of the information can be located on the Keys tab of the service's page in Dashboard. The data is as follows:

  • Service Key
  • Secret Key
  • Private Key PEM string
long appKey = 1234567890;
String secretKey = "xbv739jxzx63xrexdtrkcdkpksotctewk";
String privateKey = "-----BEGIN RSA PRIVATE KEY-----\n"+
        "MIIBOwIBAAJBALEihtCuDrAp35QpaUZ+ycfsdsCGRQGUz8nbkNwP2XsCZPqamj2A\n"+
        "QF3Tgod8tTCvvEw4X1YUuHposQnDiYkb3bkCAwEAAQJBALECAZpy9PaRQXy7TRpH\n"+
        "BLil0Z1eD4MfA+2BXeaqZ/eEqRyGzPqTYP+Ch6EB8t+xuWMoG3xgA55AxTle++TG\n"+
        "dQECIQDdadMLa2z9e8cPQ42+XU4vtPdh3P2Okewg6ST9wYOhkQIhAMzOCKcDC7Pz\n"+
        "eg3SKvG40i2/VLJfHP72gLFkdIb2+GWpAiBi5bbfve8j1hrW5Yy1gAXBZ2qsKsKS\n"+
        "4PkAxkLAmaRLEQIhAMT7ngLUwRrRoaFNdZSMyUrK7fGp3b+048666gEt5XgRAiBf\n"+
        "UHCrSnIR6lx7FksBbVZdvqNZViJL1kVVLNXa9JgHiw==\n"+
        "-----END RSA PRIVATE KEY-----\n";

AppClient appClient = clientFactory.makeAppClient(appKey, secretKey, privateKey);

Authorization Service

The authorization service allows you to interface with all facets of user authentication. It can be obtained from the service client via the auth method.

Example:

AuthService authService = appClient.auth();

Login a User/Authorize a Transaction

The methods for login and authorize are identical. The only difference being that login creates a Session and authorize does not.

Basic Authorize Example:

String authRequest = null;
String username = "myuser";
try {
    authRequest = authService.authorize(username);
} catch(BaseException e) {
    //error handling
}

Basic Login Example:

String authRequest = null;
String username = "myuser";
try {
    authRequest = authService.login(username);
} catch(BaseException e) {
    //error handling
}

Adding Context

Context can be added to both the login and authorize calls by passing a String as the first parameter of the method. The context allows the user to have confidence that they are approving the correct request.

Context Example:

String context = "Access to rear door requested";
String authRequest = null;
try {
    authRequest = authService.authorize(username, context);
} catch(BaseException e) {
    //error handling
}

Add Dynamic Policies

Authorization policies can be set statically on the Dashboard. They can also be passed dynamically with a login or authorize call. The policy an be submitted as the second argument of the method call.

Factor Quantity Example:

String context = "Two factor policy request";
AuthPolicy authPolicy = new AuthPolicy(2);
String authRequest = null;
try {
    authRequest = authService.authorize(username, context, authPolicy);
} catch(BaseException e) {
    //error handling
}

Factor Type Example:

String context = "Knowledge and Inherence factors required policy request";
boolean requireKnowledgeFactor = true;
boolean requireInherenceFactor = true;
boolean requirePossessionFactor = false;
AuthPolicy authPolicy = new AuthPolicy(requireKnowledgeFactor, requireInherenceFactor, requirePossessionFactor);
String authRequest = null;
try {
    authRequest = authService.authorize(username, context, authPolicy);
} catch(BaseException e) {
    //error handling
}

Geofence Type Example:

String context = "Taj Mahal Geofence policy request";
List<AuthPolicy.Location> locations = new ArrayList<AuthPolicy.Location>;
double radiusMeters = 175 + 20; // 1/3 the longest side of the building + 20m for GPS error.
double latitudeDegrees = 27.1750;
double longitudeDegrees = 78.0422;
locations.add(new AuthPolicy.Location(radiusMeters, latitudeDegrees, longitudeDegrees);
AuthPolicy authPolicy = new AuthPolicy(locations);
String authRequest = null;
try {
    authRequest = authService.authorize(username, context, authPolicy);
} catch(BaseException e) {
    //error handling
}

Fetching the Status of Authorization/Login Request

Warning

Although the functionality exists to fetch for a response, webhooks are the preferred method for completing a Login or Authorization request. If your implementation is not externally available or cannot receive HTTP requests, you may need to resort to polling.

To poll for the status of an existing auth request, you will use the getAuthResponse of the AuthService and pass the auth request identifier returned by with the login or authorize methods of the AuthService.

Example:

String authRequest = null;
String username = "myuser";
AuthResponse authResponse = null;
try {
    authRequest = authService.login(username);
    while (authResponse == null) {
        Thread.sleep(1000L);
        authResponse = authService.getAuthResponse(authRequest);
        if (authResponse != null) {
            boolean authorized = authResponse.isAuthorized();
            // handle authorization result
        }
    }
} catch(BaseException e) {
    //error handling
}

End a User Session (Logout)

To end the Session created by a login call, you must use the logout method. The method requires a single attribute which is the String returned from the login request.

Example:

String authRequest = null;
String username = "myuser";
AuthResponse authResponse = null;
try {
    authRequest = authService.login(username);
    while (authResponse == null) {
        Thread.sleep(1000L);
        authResponse = authService.getAuthResponse(authRequest);
        if (authResponse != null) {
            boolean authorized = authResponse.isAuthorized();
            if (authorized) {
                authService.logout(authRequest);
            }
        }
    client.auth().logout(authRequest);
} catch(BaseException e) {
   //error handling
}

Process Webhooks

Webhooks allow your service to reduce its load by not performing polling against an external API. You must create an endpoint to receive the webhook HTTP request and update your service configuration accordingly. Here is a link to the setup instructions: Server Side Events (Callbacks).

Webhooks are HTTP POST requests. Collect the query parameters from the callback endpoint and place them in a Map<String, String> object and call the handleCallback method in the auth service.

Servlet Request Example:

try {
   Map<String, String> callbackData = new HashMap<String, String>();
   for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
       if (entry.getValue().length > 0) {
           callbackData.put(entry.getKey(), entry.getValue()[0]);
       }
   }
   int signatureTimeThreshold = 300; // 5 minute threshold for request TTL
   CallbackResponse callbackResponse = authService.handleCallback(callbackData, signatureTimeThreshold);
   if (callbackResponse instanceof AuthResponseCallbackResponse) {
       boolean authorized = authResponse.isAuthorized();
       String authRequestId = authResponse.getAuthRequestId();
       String userHash = authResponse.getUserHash();
       internalAuthService.processUserResponse(authRequestId, userHash, authorized);
       System.out.println("User " + authorized ?  "accepted" : "declined");
   } elseif (callbackResponse instanceof LogoutCallbackResponse) {
       System.out.println("User Hash " + callbackResponse.getUserHash() + " has requested logged out.");
       // process users remote logout request
       String authRequest = internalAuthService.logout(callbackResponse.getUserHash());
       authService.logout(authRequest);
   }
}
catch(ApiException e) {
   //error handling
}

Auth Response Callback

The auth response callback contains information necessary to complete the auth request as well as respond to a logout callback.

Auth Request ID:The getAuthRequestId method of the AuthResponse will return the same value as returned by the authorize or login methods of the AuthService. It is required that you have a way for the callback handler to alert your internal authentication mechanism of the response from the user based on this value.
Authorized:The isAuthorized method of the AuthResponse returns a boolean value representing the response generated by the User.
User Hash:The getUserHash method of the AuthResponse returns a value unique to the User. This value will be the identifying value sent in the Logout Callback if the User performs a remote logout. If isAuthorized returns true and you wish to support remote logout, you will need to associate this value with the session created by the response.

Logout Callback

If a User executes a remote logout from a linked Device or the Dashboard, the logout callback will be triggered. Getting the user hash from the getUserHash method of the LogoutCallbackResponse allows you to identify the session(s) within your implementation that were initiated by a particular User. use that value to end the session and obtain the auth request ID to then call the logout method of the AuthService in order to alert the LaunchKey Platform that the logout was successful.

User Contributed

LaunchKey links to user contributed code as a resource to its community. LaunchKey does not in any way guarantee or warrant the quality and security of these code bases. User contributed code is supported by the creators. If you do find a link from the site to user contributed code that is malicious or inappropriate in any way, please report that link to LaunchKey immediately and we will investigate the claim. Submit any issue to LaunchKey support at https://launchkey.com./support. ×