- Home /
How to login to web application(ex.Django )?
Hi there
I'd like to login to Web sytem like Django.
My Unity's C# is this.
private IEnumerator RunLogin (string url)
{
// using POST
WWWForm form = new WWWForm ();
// csrf token
form.AddField ("csrfmiddlewaretoken", csrfToken);
string loginUsername = usernameField.text;
form.AddField ("username", loginUsername);
form.AddField ("password", passField.text);
// HEADER
Dictionary<string, string> headers = new Dictionary<string, string> ();
headers.Add ("Cookie", cookie_value);
byte[] rawData = form.data;
WWW www = new WWW (url, rawData, this.hsHeader);
yield return www;
if (www.error == null)
{
Debug.Log ("OK");
}
else
{
Debug.Log ("BAD");
}
}
And cookie_value and csrfToken is here
string cookie = "";
foreach (KeyValuePair<string, string> kv in www.responseHeaders)
{
if (kv.Key == "SET-COOKIE")
{
cookie = kv.Value;
}
}
cookie_value = cookie;
// json
JsonData data = JsonMapper.ToObject (jsonText);
bool isSuccess = false;
try
{
csrfToken = (string)data ["csrf_token"];
isSuccess = true;
Debug.Log (csrfToken);
}
But, I can't login. Error is this.
You are trying to load data from a www stream which had the following error when downloading.
403 FORBIDDEN
UnityEngine.WWW:get_text()
<RunLogin>c__Iterator8:MoveNext() (at Assets/Scripts/AvatarSystem/LoginSystem.cs:267)
Could you tell me how to login it?
Answer by oudeismetis · Apr 07, 2017 at 11:29 PM
As this is an old question, I assume you have figured this out on your own. For anyone else who comes across this...
The Django csrf token stands for cross site request forgery (https://docs.djangoproject.com/en/dev/ref/csrf/) It exists to prevent login attempts coming from outside of your Django application. This is an important security feature that you can read about in the above link. Because of this, you can't just create a form elsewhere on the internet and POST it to your Django application.
Even if you could, there are a couple of other problems I see here. You have created a security risk for your users by sending their username/password in the clear. Also, WWW by default will do a GET request to the URL. You would have to do a POST. See this for posting a form - https://docs.unity3d.com/ScriptReference/WWWForm.html
Follow-up (As I've been looking into this problem for myself)
I do realize now that you were using WWWForm in the code sample above, so disregard my one comment.
I was able to find an example project that claims to have solved this problem. I can not yet vouch for it as I have not yet dug into the code or tested it myself. https://github.com/eamonwoortman/django-unity3d-example
Your answer
Follow this Question
Related Questions
Change Web Player Size? 1 Answer
what is the draw call limit for unity web? 1 Answer
Web Player Auto Update Failed 8 Answers
Embeding Unity Game Into HTML 1 Answer
unity web player has stopped responding 0 Answers