简体   繁体   English

django-rest-auth 注销 CSRF 失败

[英]django-rest-auth logout CSRF Failed

i am using React,Redux and django rest api to build a simple website and currently learning to use django-rest-auth everything works great except the logout which gives me the CSRF Failed error. i am using React,Redux and django rest api to build a simple website and currently learning to use django-rest-auth everything works great except the logout which gives me the CSRF Failed error.

auth.js auth.js

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设置.py

REST_FRAMEWORK = {
    
    'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.AllowAny',
    ),
}

the solution was Setting default headers for axios解决方案是为 axios 设置默认标头

auth.js auth.js

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设置.py

CSRF_COOKIE_NAME = "XSRF-TOKEN"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM