Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

i'm developing authentication

[login_page localhost:8000/login/][1]

i tried to login but my state is LOGIN_FAIL

[LOGIN_FAIL][2]

I've checked it's working on postman and I know my template should have this code.

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

But, If I paste this code into Login.js, it makes an error. Like this

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>
  );
};

error code:

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

authentication trigger code:

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 code :

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',
]

Any hint would be appreciated. [1]: https://i.sstatic.net/QVXfX.jpg [2]: https://i.sstatic.net/9mWSA.jpg

like image 270
Yeon Avatar asked Oct 27 '25 01:10

Yeon


1 Answers

If you use redux, you can use redux-csrf package.

npm install redux-csrf --save

Then you can use the setCsrfToken(token) API that set the CSRF token in the Redux store.

Please refer here. enter link description here

like image 187
Dmitriy Bucaev Avatar answered Oct 28 '25 16:10

Dmitriy Bucaev