通过HTTP POST使用HttpWebRequest和HttpWebResponse从.NET进行Django身份验证

通过HTTP POST使用HttpWebRequest和HttpWebResponse从.NET进行Django身份验证,.net,django,authentication,httpwebrequest,httpwebresponse,.net,Django,Authentication,Httpwebrequest,Httpwebresponse,我正在.NET中创建一个应用程序,它将作为我已经部署的Django应用程序的第二个UI。对于某些操作,用户需要验证自己(作为Django用户)。我使用了一种非常简单的方法来实现这一点(为了简单起见,不需要加密凭据):- 第一步。我创建了一个django视图,该视图通过两个HTTPGET参数接受用户名和密码,并将它们作为关键字参数传递给django.contrib.auth.authenticate()。请参阅下面的代码: def authentication_api(request, raw_1

我正在.NET中创建一个应用程序,它将作为我已经部署的Django应用程序的第二个UI。对于某些操作,用户需要验证自己(作为Django用户)。我使用了一种非常简单的方法来实现这一点(为了简单起见,不需要加密凭据):-

第一步。我创建了一个django视图,该视图通过两个HTTPGET参数接受用户名和密码,并将它们作为关键字参数传递给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")

服务器给我一个500内部服务器错误。我的猜测是POST请求没有在.NET中正确设置。因此,我基本上需要一些关于如何从.NET发送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") 谢谢,
CM在我看来还行。我建议使用Wireshark查看restclient在标题中发送的内容,以及应用程序在标题中发送的内容。

如果您没有在两个站点之间进行任何会话共享,并且.Net站点可以访问Django应用程序的数据库,则可以直接对数据库进行身份验证。问题是如何从Python转换到.Net,但当您的哈希值不完全匹配时,它应该可以帮助您解决问题。

它现在可以工作了。HTTP标头正常,问题的根源是以下几行: Dim encoding As New UnicodeEncoding . Dim postBytes As Byte() = encoding.GetBytes(postData) 作为新的Unicode编码的Dim编码 . Dim postBytes As Byte()=encoding.GetBytes(postData)

本质上,这导致了字符字节之间的数据流为空字节。这当然不是Django身份验证在参数中所期望的。改用密码解决了这个问题

>我觉得还可以。我建议使用Wireshark查看restclient在标题中发送的内容,以及应用程序在标题中发送的内容。 这让我走上了解决问题的正确道路。我尝试使用Wireshark,但后来使用了HTTP调试器,它似乎更适合这项工作


正确的工具可以节省一个小时

没错,有很多很棒的HTTP调试工具。我只是习惯了Wireshark,从它虚无缥缈的时代一路走来。 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 Dim encoding As New UnicodeEncoding . Dim postBytes As Byte() = encoding.GetBytes(postData)