Re: Code runs until Basic Authentication or Digest Authentication

From: BMeyer (bmeyer_at_community.nospam)
Date: 10/26/05


Date: Wed, 26 Oct 2005 07:41:03 -0700

Thanks for the reply. Here's what happens:

When going to ASPX page from an ASP page, the ASPX Page_Load checks for

Try
            If Not Page.IsPostBack Then

                'Establish session vars if not already existing
                If Session("User") Is Nothing Then

                    Dim oASPSessionVar1 As New SessionVarsASPX

                    'if returns true, continue
                    If oASPSessionVar1.GetSessionVars Then

                        For i = 0 To Session.Count - 1
                            lblMain.Text = lblMain.Text & _
                                            CStr(Session.Keys(i)) & _
                                            " - " & _
                                            CStr(Session(i)) & vbCrLf

                        Next
                    Else
                        lblMain.Text = "Could not convert ASP Session Vars"

                    End If

                End If

            End If

The SessionVarsASPX page uses page "SessionVar.asp" to actually get the
session variables

---Here's "SessionVarsASPX.vb"
----------------------------------------------
Public Class SessionVarsASPX
    Inherits System.Web.UI.Page
    Dim ASPSessionVarASP As String
    Dim oContext As HttpContext

    Public Function CreateURI() As String

        ASPSessionVarASP = "SessionVar.asp"
        ' We now build a System.Uri Object to derive the correct
        ' URL to send the HTTP request to. oContext.Request.Url
        ' will contain a System.Uri Object that represents
        ' Me ASPXs URL.

        Dim oURL As System.Uri = oContext.Current.Request.Url
        Dim Path As String
        Dim i As Integer
        For i = 0 To oURL.Segments.Length - 2
            Path = Path + oURL.Segments(i)
        Next
        ASPSessionVarASP = oURL.Scheme + "://" + _
                            oURL.Host + ":" + _
                            oURL.Port.ToString() + Path + ASPSessionVarASP

        Return ASPSessionVarASP

    End Function

    Public Function GetSessionVars() As Boolean
        ' First get the Session Cookie
        Dim ASPCookieName As String = ""
        Dim ASPCookieValue As String = ""
        Dim myRequest As WebRequest
        Dim myResponse As WebResponse
        Dim PageVal As String

        Try
            If Not GetSessionCookie(ASPCookieName, ASPCookieValue) Then
                Return False
            End If

            ' Initialize the WebRequest.
            PageVal = CreateURI()
            myRequest = WebRequest.Create(PageVal)

            '7 Jun 05 - BTM
            'ASPX Session was not able to be created if basic authentication
in IIS
            'was required. Was receving 401 unauthorized error when
GetSessionVars() function
            'was being called
            'According to Microsoft Technical Support (obtained in MSDN
newsgroups on 7 Jun 05),
            'apparently, basic authentication in IIS will NOT pass on user
credentials for WebRequest.
            'WebRequest method of System.Net.WebRequest (in function
GetSessionVars()) requires
            'that user credentials be passed to web request manually.
            'X123456 is a generic domain user account used by IT and is
enough to ensure that
            'the WebRequest method passes authentication.

            '20 Jul 05 - add domain
            'Dim myCred As New
NetworkCredential(ConfigurationSettings.AppSettings("AuthString"),
ConfigurationSettings.AppSettings("AuthPwd"))
            Dim myCred As New
NetworkCredential(ConfigurationSettings.AppSettings("AuthString"),
ConfigurationSettings.AppSettings("AuthPwd"),
ConfigurationSettings.AppSettings("AuthDomain"))
            '20 Jul 05 end
            Dim myCache As New CredentialCache
            myCache.Add(oContext.Current.Request.Url, "Basic", myCred)
            myRequest.Credentials = myCache
            '7 Jun 05 - end

            myRequest.Headers.Add("Cookie: " + ASPCookieName + "=" +
ASPCookieValue)

            'debug
            
'Debug.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name())

            ' Send the request and get a response
            myResponse = myRequest.GetResponse()

            Dim receiveStream As Stream

            receiveStream = myResponse.GetResponseStream()

            Dim encode As System.Text.Encoding

            encode = System.Text.Encoding.GetEncoding("utf-8")

            Dim readStream As StreamReader

            readStream = New StreamReader(receiveStream, encode)

            'readStream = New StreamReader(myResponse.GetResponseStream(),
System.Text.Encoding.Default)

            Dim sLine As String
            Dim SessionVar As String
            Dim SessionValue As String
            Dim NumElements As Integer

            'sResponse = readStream.ReadToEnd()

            Do While readStream.Peek() >= 0

                sLine = readStream.ReadLine

                If sLine = "item:" Then

                    'next is name of item
                    SessionVar = readStream.ReadLine

                    'followed by value - need to cast as right type
                    SessionValue = readStream.ReadLine

                    If SessionValue = "True" Or SessionValue = "False" Then
                        Session(SessionVar) = CBool(SessionValue)
                    ElseIf IsNumeric(SessionValue) Then
                        Session(SessionVar) = CInt(SessionValue)
                    Else
                        Session(SessionVar) = SessionValue
                    End If

                    'else if "array="
                ElseIf sLine = "array:" Then

                    'get array name on next line
                    SessionVar = readStream.ReadLine

                    'read next line to get number of elements "elements="
                    NumElements = readStream.ReadLine

                    'dim array to save off
                    Dim ItemArray(0, NumElements) As String
                    
                    'loop through and read until end of array
                    Dim j As Integer

                    For j = 0 To UBound(ItemArray, 2)
                        'set session var equal to array
                        SessionValue = readStream.ReadLine

                        If SessionValue = "True" Or SessionValue = "False"
Then

                            ItemArray(0, j) = CBool(SessionValue)

                        ElseIf IsNumeric(SessionValue) Then

                            ItemArray(0, j) = CInt(SessionValue)

                        Else
                            ItemArray(0, j) = readStream.ReadLine

                        End If
                    Next

                    Session(SessionVar) = ItemArray

                End If

                'next

            Loop

            ' Do a bit of cleanup
            myResponse.Close()
            readStream.Close()
            Return True

        Catch Ex As Exception

            Session("Error") = "A handled error occurred when trying to
establish aspx session. " & _
                                "Please try again or contact BDS
Administrator if the problem persists."
            Session("ErrorLog") = Ex.Message.ToString & Ex.StackTrace.ToString
            Server.Transfer("ErrorPage.aspx")

        End Try

    End Function

    Private Function GetSessionCookie(ByRef ASPCookieName As String, ByRef
ASPCookieValue As String) As Boolean

        Dim loop1 As Integer
        Dim myCookie As HttpCookie
        Dim CookieArray() As String

        ASPCookieName = ""
        ASPCookieValue = ""

        ' Capture all cookie names into a string array.
        CookieArray = oContext.Current.Request.Cookies.AllKeys()

        ' Grab individual cookie objects by cookie name.
        For loop1 = 0 To CookieArray.Length - 1 Step loop1 + 1
            myCookie = oContext.Current.Request.Cookies(CookieArray(loop1))
            If myCookie.Name.StartsWith("ASPSESSION") Then
                ASPCookieName = myCookie.Name
                ASPCookieValue = myCookie.Value
                Return True
            End If
        Next

        Return False

    End Function

End Class

---And here is "SessionVar.asp" which just writes out the ASP session
variables to the Response - to be called by SessionVarsASPX.vb
----------------------------------------------
For Each Item in Session.Contents

If IsArray(Session.Contents(Item)) then
                        If UBOUND(Session.Contents(Item),2) > 0 Then
                                Response.Write "array:" & vbCrLf
                                Response.Write Item & vbCrLf
                                'now write number of elements
                                Response.Write UBOUND(Session.Contents(Item),2) & vbCrLf
                        
                        For i = 0 to UBOUND(Session.Contents(Item),2)
                                        Response.Write Session.Contents(Item)(0,i) & vbCrLf
                        Next
                        End If
                Else
                        Response.write "item:" & vbCrLf
                        Response.write Item & vbCrLf
                        Response.write Session.Contents(Item) & vbCrLf & vbCrLf
                End IF
                
                
Next