How to have “Request” events with authenticated user id?

对着背影说爱祢 提交于 2019-12-11 11:55:42

问题


I have instrumented my web application to have telemetry events sent to azure portails with the authenticated user id when available.

It works for TrackEvent coming from backend : for that once my user is authenticated , I add some information in the HttpContext.Current.Session that I am using in the TelemetryInitialiser.

public class MyTelemetryInitializer : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        if (HttpContext.Current?.Session?["user"] != null)
        {
            // Set the user id on the Application Insights telemetry item.
            telemetry.Context.User.AuthenticatedUserId = user;

            telemetry.Context.User.UserAgent = HttpContext.Current.Request.UserAgent;
            // Set the session id on the Application Insights telemetry item.
            telemetry.Context.Session.Id = HttpContext.Current.Session.SessionID;

        }
    }
}

and in Global.asax.cs

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        BundleTable.EnableOptimizations = false;
        AutoMapperConfig.RegisterMappings();

        Bootstrapper.Initialise();

        TelemetryConfiguration.Active.TelemetryInitializers.Add(new Common.MyTelemetryInitializer());
    }
}

This makes already all events coming from back-end having the authenticated id field set ( namely : Trace, Custom Event, Exception , Dependency (call to DB ).

After that I also customized the automatically created Javascript code in the Front End so that "Page View" have as well the authenticated id :

<script type='text/javascript'>
    var appInsights=window.appInsights||function(config)
    {
        function r(config){ t[config] = function(){ var i = arguments; t.queue.push(function(){ t[config].apply(t, i)})} }
        var t = { config:config},u=document,e=window,o='script',s=u.createElement(o),i,f;for(s.src=config.url||'//az416426.vo.msecnd.net/scripts/a/ai.0.js',u.getElementsByTagName(o)[0].parentNode.appendChild(s),t.cookie=u.cookie,t.queue=[],i=['Event','Exception','Metric','PageView','Trace','Ajax'];i.length;)r('track'+i.pop());return r('setAuthenticatedUserContext'),r('clearAuthenticatedUserContext'),config.disableExceptionTracking||(i='onerror',r('_'+i),f=e[i],e[i]=function(config, r, u, e, o) { var s = f && f(config, r, u, e, o); return s !== !0 && t['_' + i](config, r, u, e, o),s}),t
    }({
        instrumentationKey:'XXXXXXXXXXXXXXXXXX'
    });

    window.appInsights=appInsights;
</script>
@if (Request.IsAuthenticated)
{
    <script>
        var user = "@User.Identity.Name.Replace("\\", "\\\\")";
        appInsights.setAuthenticatedUserContext(user.replace(/[,;=| ]+/g, "_"));
    </script>
}

<script>
        appInsights.trackPageView();
</script>

For that to work it supposes that I set a Response Cookie before when authentified in the back end.

This is also working and I have my Page View events with the authenticated user id.

Nevertheless, I still have a gap : Request event does no have the authenticated user id field set.

If I examine the Requests without the field, it is both Direct Requests and all the AJAX requests that can be triggered when browsing a page. (some Going to Application defined pages, others part of the framework)

This time I have no idea of how can I make them contained the authenticated user. Any help appreciated.

来源:https://stackoverflow.com/questions/49535424/how-to-have-request-events-with-authenticated-user-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!