2012-01-11 2 views
0

Я пытаюсь создать приложение iphone, которое проведет проверку имени пользователя.Отправка Iphone на веб-сервер django дает ошибку проверки csrf

Однако, когда я перешел в имени пользователя и пароля, а также печатает журнал о jsonString, которую она получает из Интернета,

Я получаю следующее сообщение об ошибке:

2012-01-11 13:44:51.470 Different Views[53942:18903] 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html lang="en"> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
    <meta name="robots" content="NONE,NOARCHIVE"> 
    <title>403 Forbidden</title> 
    <style type="text/css"> 
    html * { padding:0; margin:0; } 
    body * { padding:10px 20px; } 
    body * * { padding:0; } 
    body { font:small sans-serif; background:#eee; } 
    body>div { border-bottom:1px solid #ddd; } 
    h1 { font-weight:normal; margin-bottom:.4em; } 
    h1 span { font-size:60; color:#666; font-weight:normal; } 
    #info { background:#f6f6f6; } 
    #info ul { margin: 0.5em 4em; } 
    #info p, #summary p { padding-top:10px; } 
    #summary { background: #ffc; } 
    #explanation { background:#eee; border-bottom: 0px none; } 
    </style> 
</head> 
<body> 
<div id="summary"> 
    <h1>Forbidden <span>(403)</span></h1> 
    <p>CSRF verification failed. Request aborted.</p> 

</div> 

<div id="info"> 
    <h2>Help</h2> 

    <p>Reason given for failure:</p> 
    <pre> 
    CSRF token missing or incorrect. 
    </pre> 


    <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when 
    <a 
    href='http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf'>Django's 
    CSRF mechanism</a> has not been used correctly. For POST forms, you need to 
    ensure:</p> 

    <ul> 
    <li>The view function uses <a 
    href='http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext'><code>RequestContext</code></a> 
    for the template, instead of <code>Context</code>.</li> 

    <li>In the template, there is a <code>{Jsrf_token 
    }</code> template tag inside each POST form that 
    targets an internal URL.</li> 

    <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use 
    <code>csrf_protect</code> on any views that use the <code>csrf_token</code> 
    template tag, as well as those that accept the POST data.</li> 

    </ul> 

    <p>You're seeing the help section of this page because you have <code>DEBUG = 
    True</code> in your Django settings file. Change that to <code>False</code>, 
    and only the initial error message will be displayed. </p> 

    <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p> 
</div> 

</body> 
</html> 

Эта ошибка происходит с веб-страницы, с которой я пытаюсь получить доступ.

на основе собственных исследований, я нашел аналогичный анс here, но я понятия не имею, как установить/получить маркер

Любой помощь будет оценена. Спасибо.

+0

это в виде веб-страницы (просмотр html и отправка формы), или вы просто отправляете данные непосредственно на какой-либо (django) просмотр? – second

+0

Я думаю из веб-представления, потому что иначе он мог бы реализовать поставленный ответ. – RickyA

+0

@Stanwin Если вы называете этот URL из webview, вы публикуете его из формы или вы положили его в bla? – RickyA

ответ

0

Из Django CSRF docs под «Как это работает»:

The CSRF protection is based on the following things:

  1. A CSRF cookie that is set to a random value (a session independent nonce, as it is called), which other sites will not have access to.

    This cookie is set by CsrfViewMiddleware. It is meant to be permanent, but since there is no way to set a cookie that never expires, it is sent with every response that has called django.middleware.csrf.get_token() (the function used internally to retrieve the CSRF token).

  2. A hidden form field with the name 'csrfmiddlewaretoken' present in all outgoing POST forms. The value of this field is the value of the CSRF cookie.

    This part is done by the template tag.

  3. For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the 'csrfmiddlewaretoken' field must be present and correct. If it isn't, the user will get a 403 error.

    This check is done by CsrfViewMiddleware.

  4. In addition, for HTTPS requests, strict referer checking is done by CsrfViewMiddleware. This is necessary to address a Man-In-The-Middle attack that is possible under HTTPS when using a session independent nonce, due to the fact that HTTP 'Set-Cookie' headers are (unfortunately) accepted by clients that are talking to a site under HTTPS. (Referer checking is not done for HTTP requests because the presence of the Referer header is not reliable enough under HTTP.)

This ensures that only forms that have originated from your Web site can be used to POST data back. (emphasis mine)

Вы не можете просто опубликовать имя пользователя и пароль, вы должны также включать в себя маркер CSRF в данных POST. Потратьте некоторое время, чтобы прочитать документы и понять, как работает CSRF.

+0

Конечно, Крис. Я займу некоторое время, чтобы понять этот компонент CSRF. Спасибо за ответ! –

+0

Любые удачи на этом? Я столкнулся с той же проблемой – JEzu

Смежные вопросы