问题
I am using django as web API for backend and React JS as web UI for frontend. User will sign up from web UI which will send a POST request to django to register with the user details. I want to protect the signup view with CSRF. Therefore I come out with steps below.
First, once the sign up page is loaded, I fire a dummy GET
request to store the csrf token with code below.
handleSend(){
let req = {
url: 'http://localhost:9000/vcubes/retrieve_token/',
method : 'GET',
withCredentials: true
}
axios(req)
}
Then, when user submit the signup form, another POST request will be fired.
const data = JSON.stringify({
'first_name': this.state.first_name,
'last_name': this.state.last_name,
'email': this.state.email,
'contact_number': this.state.contact_number,
'password1': this.state.password1,
'password2': this.state.password2,
})
let req = {
url: 'http://localhost:9000/vcubes/signup/',
method : 'POST',
headers: {
'Content-Type': 'text/plain'
},
data: data
}
axios.defaults.headers.common['X-CSRF-TOKEN'] = this.getCookie('vcubes')
With the code above, an OPTIONS will be sent to django first and then after django send back a 200 OK
, then the actual POST request will be fired.
Surprise! Django stated that I do not set CSRF cookie.
Forbidden (CSRF cookie not set.): /vcubes/signup/
[30/Oct/2017 01:30:48] "POST /vcubes/signup/ HTTP/1.1" 403 2857
My settings.py
is below. ( I only show some related code to CORS and CSRF)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'corsheaders',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'custom_user',
'vcubes',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CSRF_TRUSTED_ORIGINS = (
'localhost:8000',
'127.0.0.1:8000'
)
CSRF_COOKIE_NAME = 'vcubes'
CSRF_HEADER_NAME = 'HTTP_X_CSRF_TOKEN'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'127.0.0.1:8000'
)
CORS_ALLOW_HEADERS = (
'access-control-allow-credentials',
'access-control-allow-origin',
'access-control-request-method',
'access-control-request-headers',
'accept',
'accept-encoding',
'accept-language',
'authorization',
'connection',
'content-type',
'dnt',
'credentials',
'host',
'origin',
'user-agent',
'X-CSRF-TOKEN',
'X-CSRFToken',
'x-requested-with',
)
In views.py
@ensure_csrf_cookie
def retrieve_token(request):
return HttpResponse(status=200)
def signup(request):
print request.META
form = UserCreationForm(json.loads(request.body))
# user = form.save(commit=False)
# user.is_active = False
# user.save()
#
# mail_subject = 'Activate your account.'
# message = render_to_string('acc_active_email.html', {
# 'name': user.get_full_name(),
# 'domain': 'localhost:9000',
# 'uid': urlsafe_base64_encode(force_bytes(user.pk)),
# 'token': account_activation_token.make_token(user),
# })
# to_email = user
# email = EmailMessage(
# mail_subject, message, to=[to_email]
# )
# email.send()
return HttpResponse(status=200)
I have been spending whole day to find out the problem from google and stackoverflow but hardly get any help. Please enlighten me!
回答1:
You are missing withCredentials: true
for your post request, which means that your CSRF cookie is not sent with the request.
来源:https://stackoverflow.com/questions/47003272/django-bug-on-crsf-token