I am creating an application in .NET that will serve as the second user interface for my already deployed Django application. For some operations, users need to authenticate (as Django users). I used a super-easy way to do this (without credential encryption for simplicity): -
Step 1. I created a django view that took a username and password through two HTTP GET parameters and passed them to django.contrib.auth.authenticate () as keyword arguments. See the following code:
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")Step 2. I named it using the following code in .NET. "StrAuthURL" in the following represents a simple django url mapped to the django view above:
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, : -
django 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 Try500 . , POST .NET. , django .NET, POST.
,
CM