如何修复(CSRF 令牌丢失或不正确)react/redux + django

how to fix (CSRF token missing or incorrect ) react/redux + django

我正在开发身份验证

[login_page localhost:8000/登录/][1]

我尝试登录,但我的状态是 LOGIN_FAIL

[LOGIN_FAIL][2]

我检查过它在 postman 上工作,我知道我的模板应该有这段代码。

<form method="post">{% csrf_token %}

但是,如果我将此代码粘贴到 Login.js,则会出错。像这样

Login.js:

const Login = ({ login }) => {
  const [formData, setFormData] = useState({
    email: '',
    password: ''
  });

  const { email , password } = formData;

  const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value });

  const onSubmit = e => {
    e.preventDefault();

    login(email, password);
  };

  // Is the user authenticated
  // Redirect them to the home page

  return (
    <form method="post">{% csrf_token %}
      <div className="container mt-5"> 
        {/* <h1>회원가입</h1>
        <p>이메일로 회원가입</p> */}
        <form onSubmit={e => onSubmit(e)}>
          <div className="form-group">
            
            <input
              className="form-control"
              type="email"
              placeholder="이메일"
              name="email"
              value={email}
              onChange={e => onChange(e)}
              required
            />
          </div>
          <div className="form-group">
            <input
              className="form-control"
              type="password"
              placeholder="비밀번호"
              name="password"
              value={password}
              onChange={e => onChange(e)}
              minLength='6'
              required
            />
          </div>
          <button className='btn btn-primary' type='submit'>login</button>
        </form>
        <p className='mt-3'>
          <Link to='/signup'>signin</Link>
        </p>
        <p className='mt-3'>
        <Link to='/reset_password'>find password</Link>
        </p>
      </div>
    </form>
  );
};

错误代码:

Forbidden (CSRF token missing or incorrect.): /http//localhost:8000/auth/jwt/create/
[04/Feb/2021 01:33:26] "POST /http//localhost:8000/auth/jwt/create/ HTTP/1.1" 403 2513

认证触发码:

export const login = (email, password) => async dispatch => {
  const config = {
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const body = JSON.stringify({ email, password });

  try {
    const res = await axios.post(`${process.env.REACT_APP_API_URL}/auth/jwt/create/`, body, config);

    dispatch ({
      type: LOGIN_SUCCESS,
      payload: res.data
    });

    dispatch (load_user());
  } catch (err) {
    dispatch ({
      type: LOGIN_FAIL,
    });
  }
};

中间件代码:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

如有任何提示,我们将不胜感激。 [1]: https://i.stack.imgur.com/QVXfX.jpg [2]: https://i.stack.imgur.com/9mWSA.jpg

如果使用redux,可以使用redux-csrf包。

npm install redux-csrf --save

然后你可以使用 setCsrfToken(token) API 在 Redux store 中设置 CSRF token。

请参考这里。 enter link description here