从.NET Django的认证使用HttpWebRequest和HttpWebResponse通过HTTP POST
-
22-08-2019 - |
题
我在.NET中创建一个应用程序,将作为我已经部署Django应用程序的第二UI。对于某些操作需要用户验证自己的身份(如Django的用户)。我用超简单的方法来做到这一点(不加密为简单起见凭证): -
步骤1.我创建的通过两个HTTP GET参数接受用户名和密码Django视图和传递它们到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 URL:
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数据创建Django视图的操作的方式认证
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
服务器给我一个500内部服务器错误。我的猜测是,POST请求没有正确设置在.NET。所以基本上,我需要了解如何调用从.net发送POST数据Django的看法提供一些指导。
谢谢, CM
解决方案
看起来确定给我。我建议使用Wireshark来看看你的RESTClient实现在页眉和发送,看看您的应用程序在发送报头是什么。
其他提示
如果你没有做的两个站点和.Net网站有访问Django应用程序的数据库,你可以直接对数据库进行身份验证之间的会话共享。 这一>问题是关于如何从Python中去净,但它应该帮助你当你的哈希值不完全匹配起来。
它的工作现在。 HTTP头还行,问题的来源是下面几行:
Dim encoding As New UnicodeEncoding . Dim postBytes As Byte() = encoding.GetBytes(postData)
从本质上讲,这是导致与字符的字节之间的空字节数据流。那当然不是什么Django的认证中的参数的期望。更改为ASCIIEncoding解决了这个问题。
>看起来不错给我。我建议使用Wireshark来看看你的RESTClient实现在页眉和发送,看看您的应用程序在发送报头是什么。块引用>这让我驰向解决此正确的道路上。我试图与Wireshark的,但随后使用这似乎更适合于该作业。
HTTP调试在合适的工具可以救一个小时!