I'm trying to implement the login feature using django and vue.js. But I got an error "CSRF cookie not set" when sending the post request. I checked that I could get the csrftoken correctly by seeing the developer tools.
Below is the code of login.vue
<template>
<div class="hello">
<div class="title-color">This is a Login page.</div>
<div class="form-container">
<form v-on:submit.prevent="getCSRF">
<h2>Add User</h2>
<div class="form-group">
<label class="label">username</label>
<input class="input" type="text" v-model="username" /><br>
</div>
<div class="form-group">
<label class="label">password</label>
<input class="input" type="text" v-model="password" /><br>
</div>
<button class="button" type="submit">Submit</button>
</form>
</div>
</div>
</template>
<script>
import axios from "axios";
axios.defaults.xsrfHeaderName = 'x-csrftoken'
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.withCredentials = true;
export default {
name: "LoginView",
props: {
msg: String,
},
data() {
return {
username: "",
password: "",
csrftoken: "",
};
},
mounted() {
},
methods: {
getCSRF() {
axios({
method: "get",
url: "http://127.0.0.1:8000/csrf/",
auth: {
username: "cannot show",
password: "cannot show",
},
}).then((response) => {
this.csrftoken = response.headers['x-csrftoken'];
console.log("token is ", this.csrftoken);
axios({
method: "post",
url: "http://127.0.0.1:8000/login/",
data: {
username: this.username,
password: this.password,
},
headers: {
'X-Csrftoken': this.csrftoken,
},
auth: {
username: "Cannot show",
password: "Cannnot show",
},
}).then((response) => {
console.log(response);
})
})
},
}
};
</script>
Below is the views.py
def loginView(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
response = JsonResponse({'detail': 'OK'})
return response
else:
return Response("Invalid username or password.")
@ensure_csrf_cookie
def getToken(request):
response = JsonResponse({'detail': 'csrf cookie set'})
response['Access-Control-Expose-Headers'] = 'X-Csrftoken'
response['x-csrftoken'] = get_token(request)
return response
I could set X-Csrftoken to the request headers correctly. However, I'm not sure how I can set the cookie.
response.set_cookie('key', 'value', secure=True, samesite='None')to the loginView. andSESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = None CSRF_COOKIE_SAMESITE = Noneto the setting.py (django) But it didn't solve the problem.