【问题标题】:django-rest-auth logout CSRF Faileddjango-rest-auth 注销 CSRF 失败
【发布时间】:2021-04-14 10:58:45
【问题描述】:

我正在使用 React、Redux 和 django rest api 构建一个简单的网站,目前正在学习使用 django-rest-auth 一切正常,除了注销给我 CSRF Failed 错误。

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

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

【问题讨论】:

    标签: reactjs redux django-rest-framework


    【解决方案1】:

    解决方案是为 axios 设置默认标头

    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

    CSRF_COOKIE_NAME = "XSRF-TOKEN"
    

    【讨论】:

      猜你喜欢
      • 2013-09-23
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 2021-11-27
      • 2019-06-07
      • 2015-06-28
      • 1970-01-01
      相关资源
      最近更新 更多