Hide or prevent user accessing Token Key via View Source or Developer Tools using jQuery Ajax in ASP.Net

Last Reply on Sep 04, 2017 11:13 PM By AnandM

Posted on Sep 03, 2017 11:33 PM

How to hide or prevent users from seeing the 'Powerbi-access-Token' (towards the end of the code below) Currently anyone can view it by clicking 'View Source' or 'F12' or 'Developer Tools'.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
    <script>
        (function (powerbi) {
            'use strict';

            powerbi.Embed = Embed;

            function Embed() { }

            Embed.prototype = {
                init: function () {
                    var embedUrl = this.getEmbedUrl();
                    var iframeHtml = '<iframe style="width:100%;height:100%;" src="' + embedUrl + '" scrolling="no" allowfullscreen="true"></iframe>';
                    this.element.innerHTML = iframeHtml;
                    this.iframe = this.element.childNodes[0];
                    this.iframe.addEventListener('load', this.load.bind(this), false);
                },
                load: function () {
                    var computedStyle = window.getComputedStyle(this.element);
                    var accessToken = this.getAccessToken();

                    var initEventArgs = {
                        message: {
                            action: this.options.loadAction,
                            accessToken: accessToken,
                            width: computedStyle.width,
                            height: computedStyle.height
                        }
                    };

                    powerbi.utils.raiseCustomEvent(this.element, 'embed-init', initEventArgs);
                    this.iframe.contentWindow.postMessage(JSON.stringify(initEventArgs.message), '*');
                },
                getAccessToken: function () {
                    var accessToken = this.element.getAttribute('powerbi-access-token');

                    if (!accessToken) {
                        accessToken = powerbi.accessToken;

                        if (!accessToken) {
                            throw new Error("No access token was found for element. You must specify an access token directly on the element using attribute 'powerbi-access-token' or specify a global token at: powerbi.accessToken.");
                        }
                    }

                    return accessToken;
                },
                getEmbedUrl: function () {
                    return this.element.getAttribute('powerbi-embed');
                },
                fullscreen: function () {
                    var elem = this.iframe;

                    if (elem.requestFullscreen) {
                        elem.requestFullscreen();
                    } else if (elem.msRequestFullscreen) {
                        elem.msRequestFullscreen();
                    } else if (elem.mozRequestFullScreen) {
                        elem.mozRequestFullScreen();
                    } else if (elem.webkitRequestFullscreen) {
                        elem.webkitRequestFullscreen();
                    }
                },
                exitFullscreen: function () {
                    if (!this.isFullscreen()) {
                        return;
                    }

                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitExitFullscreen) {
                        document.webkitExitFullscreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                },
                isFullscreen: function () {
                    var options = ['fullscreenElement', 'webkitFullscreenElement', 'mozFullscreenScreenElement', 'msFullscreenElement'];
                    for (var i = 0; i < options.length; i++) {
                        if (document[options[i]] === this.iframe) {
                            return true;
                        }
                    }

                    return false;
                }
            };
        }(window.powerbi = window.powerbi || {}));
        (function (powerbi) {
            'use strict';

            powerbi.Tile = Tile;
            powerbi.Tile.prototype = powerbi.Embed.prototype;

            function Tile(element, options) {
                var me = this;

                this.element = element;
                this.options = options || {};
                this.options.loadAction = 'loadTile';
                this.getEmbedUrl = getEmbedUrl;

                this.init();

                ///////////////////////////////

                function getEmbedUrl() {
                    var embedUrl = powerbi.Embed.prototype.getEmbedUrl.call(me);
                    if (!embedUrl) {
                        var dashboardId = me.element.getAttribute('powerbi-dashboard');
                        var tileId = me.element.getAttribute('powerbi-tile');

                        if (!(dashboardId && tileId)) {
                            throw new Error('dashboardId & tileId are required');
                        }

                        embedUrl = 'https://app.powerbi.com/embed?dashboardId=' + dashboardId + '&tileId=' + tileId;
                    }

                    return embedUrl;
                }
            }
        }(window.powerbi = window.powerbi || {}));
        (function (powerbi) {
            'use strict';

            powerbi.Report = Report;
            powerbi.Report.prototype = powerbi.Embed.prototype;

            function Report(element, options) {
                var me = this;

                this.element = element;
                this.options = options || {};
                this.options.loadAction = 'loadReport';
                this.getEmbedUrl = getEmbedUrl;

                this.init();

                ///////////////////////////////

                function getEmbedUrl() {
                    var embedUrl = powerbi.Embed.prototype.getEmbedUrl.call(me);
                    if (!embedUrl) {
                        var reportId = me.element.getAttribute('powerbi-report');

                        if (!reportId) {
                            throw new Error('reportId is required');
                        }

                        embedUrl = 'https://app.powerbi.com/reportEmbed?reportId=' + reportId;
                    }

                    return embedUrl;
                }
            }
        }(window.powerbi = window.powerbi || {}));
        (function (powerbi) {
            'use strict';

            powerbi.utils = {
                raiseCustomEvent: raiseCustomEvent
            };

            function raiseCustomEvent(element, eventName, eventData) {
                var customEvent;
                if (typeof (window.CustomEvent) === 'function') {
                    customEvent = new CustomEvent(eventName, {
                        detail: eventData,
                        bubbles: true,
                        cancelable: true
                    });
                } else {
                    customEvent = document.createEvent('CustomEvent');
                    customEvent.initCustomEvent(eventName, true, true, eventData);
                }

                element.dispatchEvent(customEvent);
                if (customEvent.defaultPrevented || !customEvent.returnValue) {
                    return;
                }

                var inlineEventAttr = 'on' + eventName.replace('-', '');
                var inlineScript = element.getAttribute(inlineEventAttr);
                if (inlineScript) {
                    eval.call(element, inlineScript);
                }
            }
        }(window.powerbi = window.powerbi || {}));
        (function (powerbi) {
            'use strict';

            var embeds = [];
            var componentTypes = [];

            powerbi.get = get;
            powerbi.embed = embed;
            powerbi.init = init;

            activate();

            //////////////////////////////////    

            function activate() {
                window.addEventListener('DOMContentLoaded', init, false);
                window.addEventListener('message', onReceiveMessage, false);

                componentTypes = [
                    { type: 'powerbi-tile', component: powerbi.Tile },
                    { type: 'powerbi-report', component: powerbi.Report }
                ];
            }

            var EmbedEventMap = {
                'tileClicked': 'tile-click',
                'tileLoaded': 'tile-load',
                'reportPageLoaded': 'report-load'
            };

            function init(container) {
                container = (container && container instanceof HTMLElement) ? container : document.body;

                var components = container.querySelectorAll('[powerbi-embed]');
                for (var i = 0; i < components.length; i++) {
                    embed(components[i]);
                }
            }

            function get(element) {
                return element.powerBIEmbed || embed(element);
            }

            function embed(element) {
                var instance;

                if (element.powerBIEmbed) {
                    return element.powerBIEmbed;
                }

                for (var j = 0; j < componentTypes.length; j++) {
                    var componentType = componentTypes[j];

                    if (element.getAttribute(componentType.type) !== null) {
                        instance = new componentType.component(element);
                        element.powerBIEmbed = instance;
                        embeds.push(instance);
                        break;
                    }
                }

                return instance;
            }

            function onReceiveMessage(event) {
                if (!event) {
                    return;
                }

                try {
                    var messageData = JSON.parse(event.data);
                    for (var i = 0; i < embeds.length; i++) {
                        var embed = embeds[i];

                        // Only raise the event on the embed that matches the post message origin
                        if (event.source === embed.iframe.contentWindow) {
                            powerbi.utils.raiseCustomEvent(embed.element, EmbedEventMap[messageData.event], messageData);
                        }
                    }
                }
                catch (e) {
                    if (typeof (window.powerbi.onError) === 'function') {
                        window.powerbi.onError.call(window, e);
                    }
                }
            }
        }(window.powerbi = window.powerbi || {}));
        
    </script>
    
    <body>

    <div id="Report" 
     powerbi-access-token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ2ZXIiOiIwLjEuMCIsInR5cGUiOiJlbWJlZCIsIndjbiI6IlBCSUVtYmVkZGVkSG9zdGVkRGVtbyIsIndpZCI6IjMwN2I1Y2U0LTk3M2YtNDYyMS04YWU0LTNhZjU4MjBhOTA0MiIsInJpZCI6IjA0OWExMTY5LTE0OWMtNGEyMy1hZWI0LWNkMTlhM2Q1ZWU0NiIsImlzcyI6IlBvd2VyQklTREsiLCJhdWQiOiJodHRwczovL2FuYWx5c2lzLndpbmRvd3MubmV0L3Bvd2VyYmkvYXBpIiwiZXhwIjoxNTE0Njc4NDAwLCJuYmYiOjE1MDQ0NDcyNzR9.YYtHSL9khPZsYbRL4CYbDx6FUN_PjRG4hLgwVSLnkrQ" TextMode="Password"
     powerbi-embed="https://embedded.powerbi.com/appTokenReportEmbed?reportId=049a1169-149c-4a23-aeb4-cd19a3d5ee46" 
     powerbi-report="https://embedded.powerbi.com/appTokenReportEmbed?reportId=049a1169-149c-4a23-aeb4-cd19a3d5ee46" 
     style="height:85vh">
     <iframe style="width:100%;height:100%;" src="https://embedded.powerbi.com/appTokenReportEmbed?reportId=<The Report ID>" scrolling="no" allowfullscreen="true"></iframe></div>

</body>
</html>

 

Posted on Sep 04, 2017 04:20 AM Modified on on Sep 04, 2017 04:21 AM

Hi asifip,

What you can do is make ajax call at client side and dynamically assign the value to the attribute powerbi-access-token of Report div like below.

First make a Ajax call like below and replace YourPageName.aspx with your actual page name where you are going to write GetAccessToken web method.

jQuery

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $.ajax({
            type: "POST",
            url: "YourPageName.aspx/GetAccessToken",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {                    
                $('[id*=Report]').attr('powerbi-access-token', response.d);
            },
            failure: function (response) {
                alert(response.d);
            }
        });
    });
</script>

now coming to code behind where you can simply pass the access token to the client side without showing to the user even if user checks the page source by viewing it.

WebMethod

C#

[System.Web.Services.WebMethod]
public static string GetAccessToken()
{
    return "Your access token key goes here";
}

VB.Net

<System.Web.Services.WebMethod> _
Public Shared Function GetAccessToken() As String
    Return "Your access token key goes here"
End Function

finally pass the token key in string so that it is accessible at client side and you can view your PowerBI Chart.

 


Posted on Sep 04, 2017 07:07 AM Modified on on Sep 04, 2017 07:08 AM
asifip says:

Do I need to delete the access key data that I manually entered ?

From the beginning I noticed that the attribute powerbi-access-token doesnt look like the official attribute when I view the properties of  of Report div 

 yes you need to delete the access key added manually.

it will be bit differ but that not going to effect your Chart visualization.

asifip says:

2. Default.aspx.cs -  should I add :

[System.Web.Services.WebMethod] public static string GetAccessToken() { return "Your access token key goes here"; }

 yes you need to add method in Default.aspx.cs page only but keep in mind you need to replace the "Your access token key goes here" to your actual access token.

 

asifip says:
3. .js file - where I must add the 'ajax call ' script  

 you need to add ajax call in Default.aspx page's header section or in form tag there is no need of creating script file for it as it is small piece of code.