ASP.NET to WordPress SSO with HttpWebRequest-Collection of common programming errors
I am attempting to create a single sign on experience between an asp.net site and a wordpress site using a simple form POST method. I have built a simple php page that uses the native wordpress functions wp_insert_user and wp_signon to create user account in the mysql db and sign them in. In my asp.net ‘create new user’ page code behind, I’m using the post method of an HttpWebRequest to send the required information to the php page.
It almost works! The new wordpress user is created in the mysql database, but they are not logged in. How can I get wordpress to log them in?
UPDATE 11/29/11. I’ve added the code I used to get this working. See below
Here is my HttpWebRequest
Public Sub LoginToWordpress()
'This enables single sign on between our asp.net site and wordpress.
Try
'get the values
Dim uid As String = TxtLogin.Text
Dim pwd As String = TxtPassword.Text
'format and encode the input data
Dim encoding As New ASCIIEncoding()
Dim postData As String = ("&UserName=" & uid)
postData += ("&Pwd=" & pwd)
Dim data As Byte() = encoding.GetBytes(postData)
Dim cc As New CookieContainer()
'Prepare web request...
Dim myRequest As HttpWebRequest = WebRequest.Create("http://www.mywebsite.com/speciallogin.php")
myRequest.Method = WebRequestMethods.Http.Get
myRequest.Method = "POST"
myRequest.ContentType = "application/x-www-form-urlencoded"
myRequest.ContentLength = data.Length
myRequest.CookieContainer = cc
Dim newStream As Stream = myRequest.GetRequestStream()
'submit the php form for BuddyPress signup
newStream.Write(data, 0, data.Length)
newStream.Close()
'Get the response
Dim myResponse As HttpWebResponse = myRequest.GetResponse()
Dim reader As New StreamReader(myResponse.GetResponseStream())
'Look for cookies in the response
If Not myResponse.Cookies.Count = 0 Then
For Each c As Cookie In myResponse.Cookies
'Write the wordpress cookie to the browser
Dim cookiename As String = c.Name
Dim cCookie As New HttpCookie(cookiename)
cCookie.Value = c.Value
cCookie.Expires = c.Expires
cCookie.Domain = ".mywebsite.com"
cCookie.Path = "/"
Response.Cookies.Add(cCookie)
Next
End If
myResponse.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Here is the php page (speciallogin.php)