Thursday, August 28, 2014

ASP - Function to Get Windows Logon UserName

This requires that you have some form of authentication enabled on the web site configuration.  I prefer Windows Authentication, but forms or basic might also suffice.  Basically, regardless of the web browser, as long as some form of authentication is required, and the user provides it (or the browser hands it over silently, like IE usually does, cough-cough), it will spew forth the "logon_user" or "remote_user" server variable.  Using that, you can parse out a NetBIOS domain prefix, such as "contoso\dumbass" to return just the "dumbass" part.

[asp]
<%
Function Get_UserName()
    Dim tmp, result
    result = ""
    tmp = Trim(Request.ServerVariables("LOGON_USER"))
    If tmp = "" Then
        tmp = Trim(Request.ServerVariables("REMOTE_USER"))
    End If
    If tmp <> "" Then
        If InStr(tmp, "\") > 0 Then
            arrtmp = Split(tmp,"\")
            result = Lcase(arrtmp(1)
        Else
            result = Lcase(tmp)
        End If
    End If
    Get_UserName = result
End Function

' test it out...

If Get_UserName() = "dave" Then
    Response.Write "yay!  it's dave!"
Else
    Response.Write "boo.  it's not dave. bummer."
End If
%>
[/asp]

No comments:

Post a Comment