我在.NET中創建了一個應用程序,該應用程序將作爲我已部署的Django應用程序的第二個UI。對於用戶需要進行身份驗證的一些操作(如Django用戶)。我使用了一種非常簡單的方式來完成此操作(無簡單加密憑證): -從.NET使用HttpWebRequest和HttpWebResponse通過HTTP POST進行Django身份驗證
第1步。我創建了一個django視圖,它通過兩個HTTP GET參數接受用戶名和密碼,並將它們傳遞給django.contrib .auth.authenticate()作爲關鍵字參數。請參閱下面的代碼:
def authentication_api(request, raw_1, raw_2): user = authenticate(username=raw_1, password=raw_2) if user is not None: if user.is_active: return HttpResponse("correct", mimetype="text/plain") else: return HttpResponse("disabled", mimetype="text/plain") else: return HttpResponse("incorrect", mimetype="text/plain")
第2步。我在.NET中使用以下代碼調用此代碼。在下面的「strAuthURL」 representes映射到上述Django的視圖簡單的Django網址:
Dim request As HttpWebRequest = CType(WebRequest.Create(strAuthURL), HttpWebRequest) Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse) Dim reader As StreamReader = New StreamReader(response.GetResponseStream()) Dim result As String = reader.ReadToEnd() HttpWResp.Close()
這完美的作品,但它只不過是一個證明的概念更多。
現在我想,所以我做了以下通過HTTP POST做到這一點: -
我使用POST數據
def post_authentication_api(request): if request.method == 'POST': user = authenticate(username=request.POST['username'], password=request.POST['password']) if user is not None: if user.is_active: return HttpResponse("correct", mimetype="text/plain") else: return HttpResponse("disabled", mimetype="text/plain") else: return HttpResponse("incorrect", mimetype="text/plain")
I have tested this using restclient and this view works as expected. However I can't get it to work from the .NET code below:
Dim request As HttpWebRequest = CType(WebRequest.Create(strAuthURL), HttpWebRequest) request.ContentType = "application/x-www-form-urlencoded" request.Method = "POST" Dim encoding As New UnicodeEncoding Dim postData As String = "username=" & m_username & "&password=" & m_password Dim postBytes As Byte() = encoding.GetBytes(postData) request.ContentLength = postBytes.Length Try Dim postStream As Stream = request.GetRequestStream() postStream.Write(postBytes, 0, postBytes.Length) postStream.Close() Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse) Dim responseStream As New StreamReader(response.GetResponseStream(), UnicodeEncoding.Unicode) result = responseStream.ReadToEnd() response.Close() Catch ex As Exception MessageBox.Show(ex.ToString) End Try
創造了做認證Django視圖服務器給我一個500內部服務器錯誤。我的猜測是POST請求沒有在.NET中正確設置。所以我基本上需要一些關於如何從.NET發送POST數據來調用django視圖的指導。
感謝, CM
沒錯,那裏有很棒的HTTP調試工具。從Ethereal開始,我就習慣了Wireshark。 – Strelok 2008-12-17 23:31:33