既にデプロイされている Django アプリの 2 番目の UI として機能するアプリケーションを .NET で作成しています。一部の操作では、ユーザーは自分自身を認証する必要があります (Django ユーザーとして)。これを行うには、非常に簡単な方法を使用しました(簡単にするために資格情報を暗号化せずに):-
ステップ 1. 2 つの HTTP GET パラメーターを介してユーザー名とパスワードを受け取り、それらをキーワード引数として django.contrib.auth.authenticate() に渡す django ビューを作成しました。以下のコードを参照してください。
def authentication_api (リクエスト、raw_1、raw_2):
ユーザー = 認証 (ユーザー名 = raw_1、パスワード = raw_2)
ユーザーが None でない場合:
user.is_active の場合:
return HttpResponse("正しい", mimetype="text/plain")
そうしないと:
return HttpResponse("disabled", mimetype="text/plain")
そうしないと:
return HttpResponse("正しくない", mimetype="text/plain")
ステップ 2. .NET で次のコードを使用してこれを呼び出しました。次の「strAuthURL」は、上記の Django ビューにマップされた単純な Django URL を表しています。
Dim request As HttpWebRequest = CType(WebRequest.Create(strAuthURL), HttpWebRequest)
薄暗い応答として HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
Dim リーダー As StreamReader = New StreamReader(response.GetResponseStream())
文字列として薄暗い結果 = reader.ReadToEnd()
HttpWResp.Close()
これは概念実証にすぎませんが、問題なく動作します。
これをHTTP POST経由で実行したいので、次のことを行いました: -
POSTデータを使用して認証を行うためのdjangoビューを作成しました
def post_authentication_api (リクエスト):
request.method == 'POST' の場合:
user = authenticate(username=request.POST['username'], password=request.POST['password'])
ユーザーが None でない場合:
user.is_active の場合:
return HttpResponse("正しい", mimetype="text/plain")
そうしないと:
return HttpResponse("disabled", mimetype="text/plain")
そうしないと:
return HttpResponse("正しくない", 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 エンコーディング As New UnicodeEncoding
Dim postData As String = "username=" & m_username & "&password=" & m_password
Dim postBytes As Byte() = encoding.GetBytes(postData)
request.ContentLength = postBytes.Length
試す
Dim postStream As Stream = request.GetRequestStream()
postStream.Write(postBytes, 0, postBytes.Length)
postStream.Close()
薄暗い応答として HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
Dim responseStream As New StreamReader(response.GetResponseStream(), UnicodeEncoding.Unicode)
結果 = responseStream.ReadToEnd()
response.Close()
ex を例外としてキャッチ
MessageBox.Show(ex.ToString)
エンドトライ
サーバーから 500 内部サーバー エラーが発生しました。私の推測では、.NET で POST 要求が適切に設定されていません。したがって、POST データを送信する .NET から django ビューを呼び出す方法について、基本的にガイダンスが必要です。
ありがとう、CM