Capture User’s Last Successful Login with Portal Web API

image

Hey Power Pages developers! Are you sitting there scratching your head wondering why the Authentication/LoginTrackingEanbled site setting isn’t working? Unfortunately it has been deprecated 😭😭😭😭. This saddened me a lot because I utilize the Last Successful Login date field on the Contact table for a lot of reporting and automation using Power Automate. In this article I will demonstrate how you can use the Portal WebAPI with a little Javascript/Liquid to populate that field. Before we dive in, here are a few other options you might consider:

  • Power Automate: Use a Flow to capture the data, a good example of how to implement can be found here: Last Successful Login on Contact record by Prasad Motupalli. The one thing this was missing for me though was security which could be a concern with the http trigger not requiring authentication. I want to be sure that the person updating the data is an authenticated user.
  • Application Insights: You can track additional details surrounding users on your site by using liquid and adjusting the application insights JS on your site. Details on how to do that can be found here: PowerApps Portals tracking using Azure Application Insights by Oleksandr Olashyn. I have added this code to my site and will be using it for more detailed reports. One thing missing from this approach is having the data directly in Dataverse for reporting or easily running Power Automate against that data.

Instructions

To populate the Last Successful Login field on the Contact table using the Web API, we’ll first need to enable table permissions and grant WebAPI access to that field. Finally we will drop in some JavaScript/Liquid code which will be used to make the Web API call. Big thanks to 🎉🎉 Marty Sease 🎉🎉 for all his help writing that code, and doing so in a way that reduces any negative performance impacts by using sessions variables.

Create Table Permissions

To get started navigate to the Portal Management app.

image

Create a new Table permission that will allow for a user to update and read their own contact record.

image

Add the Authenticated User web role to the Table Permission.

image

Create Web API Settings

Create two Site Settings that will enable the Web API for the Contact record and allow access to the adx_identity_lastsuccessfullogin, which is the logical name for the field displayed on the Contact form.

Note: In the site settings below we are using the out of the box column provided in the default portal solution. You are not required to use that field, you can use your own custom date column and use the logical name of that column here instead.

Name Value
Webapi/contact/enabled true
Webapi/contact/fields adx_identity_lastsuccessfullogin

image

DROP THE CODE!!

Finally we will navigate to the Enable Traffic Analysis section of the App. From here select the website and then copy the code below and click save. If you are also doing Application Insights tracking (which is always a good idea), just copy this code below the code for that.

image

Code to be copied into the Tracking Code content snippet:

<script type = "text/javascript" > 
{% if user %}
    (function(webapi, $) {
        function safeAjax(ajaxOptions) {
            var deferredAjax = $.Deferred();
            shell.getTokenDeferred().done(function(token) {
                // add headers for AJAX
                if (!ajaxOptions.headers) {
                    $.extend(ajaxOptions, {
                        headers: {
                            "__RequestVerificationToken": token
                        }
                    });
                } else {
                    ajaxOptions.headers["__RequestVerificationToken"] = token;
                }
                $.ajax(ajaxOptions)
                    .done(function(data, textStatus, jqXHR) {
                        validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve);
                    }).fail(deferredAjax.reject); //AJAX
            }).fail(function() {
                deferredAjax.rejectWith(this, arguments); // on token failure pass the token AJAX and args
            });
            return deferredAjax.promise();
        }
        webapi.safeAjax = safeAjax;
    })(window.webapi = window.webapi || {}, jQuery)
    const loginCacheKey = "lastLoginKey";
    if (!sessionStorage.getItem(loginCacheKey)) {
        const now = new Date();
        sessionStorage.setItem(loginCacheKey, now);
        webapi.safeAjax({
            type: "PATCH",
            url: "/_api/contacts({{ user.contactid }})",
            contentType: "application/json",
            data: JSON.stringify({
                "adx_identity_lastsuccessfullogin": now
            })
        });
    }
{% else %}
  const loginCacheKey = "lastLoginKey";
  sessionStorage.removeItem(loginCacheKey);
{% endif %} 
</script>

Thats it! Now when a user logs into your Power Pages portal you will be able to capture the Last Successful Login date field. If you don’t see it happen right away make sure you clear the Portal Cache then try logging out and back in again.

Comments

Popular posts from this blog

Add User As Local Administrator On Domain Controller

Calling Dataverse Web API in PowerShell using Client Credentials

Windows Server 2008R2 VMs Shut Down After 1 to 2 Hours