首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >django-rest-auth注销CSRF失败

django-rest-auth注销CSRF失败
EN

Stack Overflow用户
提问于 2021-04-14 18:58:46
回答 1查看 44关注 0票数 0

我正在使用React,Redux和django rest api来构建一个简单的网站,目前正在学习使用django-rest-auth,除了注销之外,一切都很好,这会给我一个CSRF失败的错误。

auth.js

代码语言:javascript
复制
export const logout = token => {
    localStorage.removeItem('expirationDate');
    const requestOptions = {
        method: "POST",
        headers: { "Content-Type": "application/json",
        'X-CSRFToken':token,
                },
    };
    fetch("/rest-auth/logout/", requestOptions)
    return {
        type: actionTypes.AUTH_LOGOUT
    };
}
export const authLogin = (username, password) => {
    return dispatch => {
        dispatch(authStart());
        axios.post('http://127.0.0.1:8000/rest-auth/login/', {
            username: username,
            password: password
        })
        .then(res => {
            const token = res.data.key;
            const expirationDate = new Date(new Date().getTime() + 3600 * 1000);
            localStorage.setItem('token', token);
            localStorage.setItem('expirationDate', expirationDate);
            dispatch(authSuccess(token));
            dispatch(checkAuthTimeout(3600));
        })
        .catch(err => {
            dispatch(authFail(err))
        })
    }
}

settings.py

代码语言:javascript
复制
REST_FRAMEWORK = {
    
    'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.AllowAny',
    ),
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-14 21:31:07

解决方案是为axios设置缺省标头

auth.js

代码语言:javascript
复制
axios.defaults.xsrfHeaderName = "X-CSRFToken";
axios.defaults.withCredentials = true

export const logout = () => {
    localStorage.removeItem('token');
    axios.post("/rest-auth/logout/", {})
    return {
        type: actionTypes.AUTH_LOGOUT
    };
}

settings.py

代码语言:javascript
复制
CSRF_COOKIE_NAME = "XSRF-TOKEN"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67090412

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档