Code Samples
Here is some example code on how to retrieve the MCP Shield Javascript snippet and include it in the web page delivered to the user. Be sure the consult the API reference for the exact specification and Integration Patterns for integration options.
Also, be sure to adhere to Best Practices.
- PHP
- Java
- C#
- Go
- Node.js
define('ServiceKey', 'SERVICE_ID');
//In case of Missing URL Parameter @uniqid Replace @{UNIQUE_TRANSACTION_ID} With Actual Transaction ID
define('TransactionID', (isset($_GET['uniqid']) ? $_GET['uniqid'] : time()));
define('APIURL', 'https://sg.apiserver.shield.monitoringservice.co/'.ServiceKey.'/'.TransactionID.'/JS');
define('ApiSnippetUrl', 'https://uk.api.shield.monitoringservice.co/');
$secreteHeaderParams = array(
'Upgrade-Insecure-Requests'
);
$head = apache_request_headers();
if(is_array($head) !== false){
foreach ($secreteHeaderParams as $shp) {
if(array_key_exists($shp, $head)){
unset($head[$shp]);
}
}
$h = urlencode(json_encode($head));
}else{
$h = "";
}
$ctx = stream_context_create(array('http' => array('user_agent' => $_SERVER['HTTP_USER_AGENT'], 'timeout' => 5)));
$params = http_build_query(array(
'lpu' => urlencode((isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http')."://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']),
'timestamp' => str_replace('.', '', isset($_SERVER['REQUEST_TIME_FLOAT']) ? $_SERVER['REQUEST_TIME_FLOAT'] : microtime(true)),
'user_ip' => $_SERVER['REMOTE_ADDR'],
'head' => $h
));
$response = json_decode(file_get_contents(APIURL."?".$params, null, $ctx));
if(!empty($response)){
$source = $response->source;
$uniqid = $response->uniqid; // Unique Key To Use For Block API Call
}else{
$uniqid = md5($params['user_ip'].'-'.TransactionID.'-'.microtime(true)); // Unique Key To Use For Block API Call
$source = "(function(s, o, u, r, k){
b = s.URL;
v = (b.substr(b.indexOf(r)).replace(r + '=', '')).toString();
r = (v.indexOf('&') !== -1) ? v.split('&')[0] : v;
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.setAttribute('crossorigin', 'anonymous');
a.src = u+'script.js?ak='+k+'&lpi='+r+'&lpu='+encodeURIComponent(b)+'&key=$uniqid&_headers=".base64_encode($h)."'';
m.parentNode.insertBefore(a, m);
})(document, 'script', '".ApiSnippetUrl."', 'uniqid', '".ServiceKey."');";
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="jdk.internal.org.objectweb.asm.tree.TryCatchBlockNode"%>
<%@ page import="java.security.MessageDigest"%>
<%@ page import="java.util.*"%>
<%@ page import="java.net.*"%>
<%@ page import="org.json.*"%>
<%@ page
import="java.io.*,java.io.DataOutputStream,java.io.BufferedReader"%>
<%@ page
import="java.io.*,java.util.*,java.net.HttpURLConnection,java.net.URL"%>
<%
String ServiceKey = "{ServiceKey Get After Service Registration}";
String TranscationVariableName = "{Unique URL Identifier}";
String TransactionID;
String source;
String uniqid;
if (request.getParameter(TranscationVariableName) == null) {
long tmp = new java.util.Date().getTime();
TransactionID = Long.toString(tmp);
} else {
TransactionID = request.getParameter(TranscationVariableName);
}
String APIURL = "http://sg.apiserver.shield.monitoringservice.co/"+ServiceKey+"/"+TransactionID+"/JS";
String ApiSnippetUrl = "https://uk.api.shield.monitoringservice.co/";
Enumeration headers = request.getHeaderNames();
JSONObject headersObj = new JSONObject();
while (headers.hasMoreElements()) {
String name = (String) headers.nextElement();
String value = (String) request.getHeader(name);
headersObj.put(name, value);
}
String headersString = headersObj.toString();
String url = request.getRequestURL().toString();
String queries = request.getQueryString();
if(queries != null) {
url = url + "?" + queries;
}
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append("?lpu=" + URLEncoder.encode(url, "UTF-8") + "&timeStamp=" + System.nanoTime() + "&user_ip=" + request.getRemoteAddr() + "&head=" + URLEncoder.encode(headersObj.toString(), "UTF-8"));
URL obj = new URL(APIURL + urlBuilder.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", request.getHeader("User-Agent"));
int responseCode = con.getResponseCode();
System.out.println("MCP Shield Response Code: " + responseCode);
String result = "";
if (responseCode == 200){
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String _response = "";
while ((_response = in.readLine()) != null) {
result += _response.toString();
}
in.close();
JSONObject json = null;
json = new JSONObject(result);
uniqid = json.getString("uniqid");
source = json.getString("source");
String loadTime = con.getHeaderField("X-Loaded");
} else if (responseCode == 403) {
System.out.println("MCP Shield, Blocked, You are not allowed to load Shield Kit");
source = "console.log('MCP Shield, Blocked');";
uniqid = "";
} else {
String uniqueId = TransactionID + "-" + request.getRemoteAddr() + "-" + System.nanoTime();
String plainText = uniqueId;
MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5");
mdAlgorithm.update(plainText.getBytes("UTF-8"));
byte[] digest = mdAlgorithm.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
String hex = Integer.toHexString(0xFF & digest[i]);
if (hex.length() < 2) {
hex = "0" + hex;
}
hexString.append(hex);
}
uniqid = hexString.toString();
String headersBase64 = java.util.Base64.getEncoder()
.encodeToString(headersObj.toString().getBytes("UTF-8"));
source = "(function(s, o, u, r, n, k){";
source += "a = s.createElement(o);";
source += "m = s.getElementsByTagName(o)[0];";
source += "a.async = 1;";
source += "a.setAttribute(\"crossorigin\", \"anonymous\");";
source += "a.src = u+'script.js?ak='+k+'&lpi='+r+'&lpu='+n+'&key=" + uniqid + "&_headers=" + headersBase64 + "';";
source += "m.parentNode.insertBefore(a, m);";
source += "})(document, 'script', '" + ApiSnippetUrl + "', '" + TransactionID + "', '" + URLEncoder.encode(url, "UTF-8") + "', '" + ServiceKey + "');";
}
out.flush();
//Variable uniqid will be used to call Block API with param named uniqid at the endpoint /appblock
%>
string ServiceKey = "{Your Service ID}"; //Service Key
string ApiSnippetUrl = "https://uk.api.shield.monitoringservice.co/";
string TransactionID;
string uniqid;
string source = "";
int unixTimestamp = (int)DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var request = HttpContext.Request;
// Transaction ID
if (string.IsNullOrEmpty(request.Query["gclid"]))
TransactionID = unixTimestamp.ToString();
else
TransactionID = request.Query["gclid"];
string APIURL = $"https://sg.apiserver.shield.monitoringservice.co/{ServiceKey}/{TransactionID}/JS";
// Collect headers
var collection = new Dictionary<string, string>();
foreach (var h in request.Headers)
{
collection[h.Key] = h.Value!;
}
string JsonHeader = JsonConvert.SerializeObject(collection);
var client = new RestClient(APIURL);
var req = new RestRequest();
req.AddParameter("lpu", $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}");
req.AddParameter("timestamp", unixTimestamp);
req.AddParameter("user_ip", HttpContext.Connection.RemoteIpAddress?.ToString());
req.AddParameter("head", JsonHeader);
var res = await client.ExecuteAsync(req);
if (res.StatusCode == System.Net.HttpStatusCode.OK)
{
dynamic response = JsonConvert.DeserializeObject(res.Content);
uniqid = response.uniqid;
source = response.source;
}
else
{
string md5String = $"{HttpContext.Connection.RemoteIpAddress}-{TransactionID}-{unixTimestamp}";
using var md5 = MD5.Create();
var hash = md5.ComputeHash(Encoding.ASCII.GetBytes(md5String));
// Base64 headers
string headersBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonHeader));
string encodedHeaders = Uri.EscapeDataString(headersBase64);
uniqid = BitConverter.ToString(hash).Replace("-", "").ToLower();
source = $@"(function(s,o,u,r,k){{
b=s.URL;
a=s.createElement(o),
m=s.getElementsByTagName(o)[0];
a.async=1;
a.setAttribute('crossorigin','anonymous');
a.src=u+'script.js?ak='+k+'&lpi='+r+'&lpu='+encodeURIComponent(b)+'&key={uniqid}&_headers={encodedHeaders}';
m.parentNode.insertBefore(a,m);
}})(document,'script','{ApiSnippetUrl}','{TransactionID}','{ServiceKey}');";
}
//Variables
//1) uniqid // Need TO Use While calling block API
//2) source // Embed in head tag inside script tag
package main
import (
"crypto/md5"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
)
func homeLink(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to shield api server")
}
func redr(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "SCHEME:", r.URL.Scheme, "HOST:", r.Host, "PATH", r.URL.Path)
}
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/integrate", shieldIntegration)
router.HandleFunc("/", homeLink)
log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", router))
}
func shieldIntegration(w http.ResponseWriter, request *http.Request) {
var serviceId = "xx-xx-xx-xx"
var ApiSnippetUrl = "https://uk.api.shield.monitoringservice.co/"
var transactionId string
query := request.URL.Query()
gclid := query.Get("tid")
if gclid == "" {
transactionId = strconv.FormatInt(time.Now().Unix(), 10)
} else {
transactionId = gclid
}
var apiUrl = "https://sg.apiserver.shield.monitoringservice.co/" + serviceId + "/" + transactionId + "/JS"
var mHeader = make(map[string]string)
for name, headers := range request.Header {
name = strings.ToLower(name)
for _, h := range headers {
mHeader[name] = h
}
}
jsonHeader, err := json.Marshal(mHeader)
if err != nil {
fmt.Println(err.Error())
return
}
jsonHeaderStr := string(jsonHeader)
shieldRequest, _ := http.NewRequest("GET", apiUrl, nil)
shieldRequest.Header.Set("user-agent", request.UserAgent())
q := shieldRequest.URL.Query()
q.Add("lpu", request.Host+""+request.URL.RequestURI())
q.Add("timestamp", strconv.FormatInt(time.Now().Unix(), 10))
q.Add("user_ip", request.RemoteAddr)
q.Add("head", jsonHeaderStr)
shieldRequest.URL.RawQuery = q.Encode()
timeout := time.Duration(100 * time.Second)
client := http.Client{Timeout: timeout}
shieldResponse, err := client.Do(shieldRequest)
if err != nil {
fmt.Println("response error")
}
if shieldResponse.StatusCode == 200 {
defer shieldResponse.Body.Close()
var data map[string]interface{}
json.NewDecoder(shieldResponse.Body).Decode(&data)
uniqID := data["uniqid"].(string)
source := data["source"].(string)
fmt.Println("uniqid:", uniqID)
fmt.Println("source:", source)
return
}
md5String := []byte(request.RemoteAddr + "-" + transactionId + "-" + strconv.FormatInt(time.Now().Unix(), 10))
unqId := fmt.Sprintf("%x", md5.Sum(md5String))
headersBase64 := base64.StdEncoding.EncodeToString(jsonHeader)
source := `"(function(s,o,u,r,k){b=s.URL;
a=s.createElement(o),
m=s.getElementsByTagName(o)[0];
a.async=1;
a.setAttribute('crossorigin','anonymous');
a.src=u+'script.js?ak='+k+
'&lpi='+r+
'&lpu='+encodeURIComponent(b)+
'&key=` + unqId + `&_headers=` + headersBase64 + `';
m.parentNode.insertBefore(a,m);
})(document,'script','` + ApiSnippetUrl + `','` + transactionId + `','` + serviceId + `');"`
fmt.Println("source:", source)
fmt.Println("uniqid:", unqId)
}
MCP Shield Node Moduleβ
How to Integrateβ
1. Install via npmβ
npm install https://docs.mcpshield.com/node/latest/mcpshield.tgz
2. Load MCP Shield moduleβ
const MCPShield = require('mcpshield');
3. Create MCP Shield Clientβ
const mcpShieldClient = new MCPShield(
'{SERVICE KEY}',
'{UNIQUE URL IDENTIFIER}',
options
);
3.1 Supported Optionsβ
{
ssl: true || false,
active_dc: 'uk' || 'sg',
timeout: ms,
exculsionList: ['css', 'js']
}
4. Callbacksβ
successCallbackβ
Returns:
{
"uniqid": "String",
"timestamp": "Number",
"source": "String"
}
deniedCallbackβ
Service is not active in Shield.
errorCallbackβ
An error occurred.
excludedCallbackβ
Endpoint is excluded from MCP Shield processing.
5. Usage Notesβ
- On
successCallback, inject source into<head>inside ascripttag - Store uniqid for Block API requests
- Ensure active_dc is set correctly (uk or sg)