NTLM login with Anonymous fallback

At work we run a fairly large extranet SharePoint farm where some sites are anonymous access. Normally in SharePoint, when a domain user on a domain workstation hits a SharePoint site that requires authentication, it automatically logs them in. Unfortunately, in that same scenario but the site is anonymous, the user will not get logged in. The user then has to realize this and click sign in at the top right. Also because SharePoint security trims the user interface so you only see what you have access to see.  Many times users will complain they have lost their permissions or something because they won’t be able to find their normal way of doing things when they don’t realize they aren’t logged in.

Several years ago I set out on a mission to fix this. The best solution I found was posted here: http://blogs.claritycon.com/blogs/ryan_powers/archive/2007/06/12/3187.aspx. I was able to take what he had done and modify it for SharePoint. So since authentication is tied to the session, we only need to run our code once per session. So the trick is determining when a new session is starting and running the code. I was unsuccessful in getting the SessionStateModule.Start event to fire and not fire when I needed it to so I decided to use the PostAcquireRequestState event and check on each request if I have already run my code or not. I’m using a session variable to ensure I only run the code once per session. Essentially what the code does is the first time a new session is started instead of outputting the normal html requested, the httpmodule outputs some javascript.

This javascript makes a web call to /_layouts/authenticate.aspx which is the page used to login you into SharePoint. This call is done in a way so if an error happens (such as not being able to login) that error is trapped and the end user never sees the gray login box. Whether the login is successful or not the javascript then refreshes the page. At this point the httpmodule will not change the html output because it’s already been run on the current session so the real requested html is sent and if the authentication was successful, the user is shown as being logged into the site.

Also notice I added the querystring Source=%2F%5Flayouts%2Fimages%2Fblank%2Egif to the authenticate url. Normally when authenticate.aspx is called without this querystring it will redirect the user to the current site’s homepage. Since this causes extra execution time running webparts and rendering the page as well as the end user never sees this page because the call is being done in javascript, I found it was much faster to send the user to an image after authenticating. So i chose the blank.gif which is available on any SharePoint installation. This requires much less resources on the server as well as showing the actual page faster to the browser.

I also do a few checks before I output the javascript. Since automatic ntlm login only works in IE and windows, I check the useragent for that condition. I also check to make sure the request isn’t for infopath form services (/_layouts/formserver.aspx) because we had some issues with the module not playing nice with those services.

Anyway, here’s the code:

public class MixedAuthenticationScreeningModule : IHttpModule
{
    private const string NO_SCRIPT_MESSAGE = "Your browser does not support JavaScript or has scripting disabled, which prevents credentials screening from working.";
    private string _requiresAuthenticationUrl = "/_layouts/Authenticate.aspx?Source=%2F%5Flayouts%2Fimages%2Fblank%2Egif";
 
    void IHttpModule.Init(HttpApplication context)
    {
        context.PostAcquireRequestState += new EventHandler(context_PostAcquireRequestState);
    }
 
    void context_PostAcquireRequestState(object sender, EventArgs e)
    {
        MixedModeLogin();
    }
 
    private void MixedModeLogin()
    {
        HttpContext context = HttpContext.Current;
        if (context.Session == null) return;
        if (context.Request.RequestType != "GET") return;
        if (context.Session["MixedModeAuth"] != null) return;
        context.Session["MixedModeAuth"] = false;
        if (IsWin32Ie(context) == false) return;
        if (context.Request.RawUrl.ToLower().Contains("/_layouts/formserver.aspx")) return;
        context.Session["MixedModeAuth"] = true;
        RenderScreeningHtml(context.Request.RawUrl, context.Response);
    }
 
    private bool IsWin32Ie(HttpContext context)
    {
        string userAgent = context.Request.UserAgent;
        return userAgent != null && userAgent.IndexOf("MSIE") >= 0 && userAgent.IndexOf("Windows") >= 0;
    }
 
    private void RenderScreeningHtml(string currentUrl, HttpResponse response)
    {
        string screeningFailedUrl = currentUrl;
        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.Cache.SetExpires(DateTime.Now.AddDays(-1)); //or a date much earlier than current time
        response.Write("<!--DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"--><html></html><head></head><script type="text/javascript" language="javascript">  function canAuthenticate() { try { var dom = new ActiveXObject("Msxml2.DOMDocument");  dom.async = false; dom.load("" + _requiresAuthenticationUrl + "");} catch(e) { return false; }  return true;}  canAuthenticate(); window.location.href=window.location.href; </script><noscript></noscript>");
        try
        {
            response.End();
        }
        catch { }
    }
 
    void IHttpModule.Dispose()
    {
    }
}

Here is what the user’s see when the javascript code is trying to log them in:

Here is what shows up in fiddler when someone is logged in successfully. Notice the first time default.aspx is called it’s only 763 bytes and the second time 61 KB. That’s because the first time only the javascript was sent to the browser, but the second time the whole html for the page was sent to the browser. You can also see where the authentication happens and since it was successful you can see where the blank.gif was loaded.

 

Here is what shows up in fiddler when someone is not logged in successfully, thus it falls back to anonymous. You can see that the authentication doesn’t happen and blank.gif is never called.

2 Replies to “NTLM login with Anonymous fallback”

  1. I saw in an answer from you on a StackOverflow question that you got this to work in Chrome as well. Can you please provide some more information about how you managed to do that? I haven’t found a way to do that since Chrome cannot create ActiveXObjects.
    var dom = new ActiveXObject(“Msxml2.DOMDocument”);

    Link to the StackOverflow answer: http://stackoverflow.com/a/17046512/2082340

  2. Well, I did get it working in chrome but it adversely affected firefox so I pulled that code out. Unfortunately I never checked in that code so I don’t have the exact details on what I did but it was similar by using a xmlrequest to the auth page wrapped in a try catch.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*