首页 > 解决方案 > React Native 中的 Csrf 令牌发布

问题描述

我使用 Node 和 Express 作为框架制作了一个网站。现在我们正在转向 React Native 移动应用程序。在制作登录页面时,我提出了一个帖子请求,如下所示

index.js

import React, { Component } from 'react'
import {
  View,
  TextInput,
  Text,
  Button,
  Alert,
} from 'react-native';
import styles from './styles'

class Home extends Component {
  constructor(props){
    super(props)
    state = {email: "", password: ""}
  }

  checkLogin(){
    const { email, password } = this.state;
    if(email ==="admin" || password === "admin" || true){
        fetch('http://localhost:3021/user/signin', {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            email: email,
            password: password,
          }),
        })
        .then((response) => {
          console.log(response)
        })
        .catch((error) => {
          console.error(error);
        })
      }
      else{
      Alert.alert('Error', 'Email/Password mismatch', [{
        text: 'Okay',
      }])
    }
  }

  render(){
    const {heading, input, parent} = styles

    return (
      <View style={parent}>
        <Text style={heading}> Login into the Application </Text>
        <TextInput style={input} placeholder="Email" onChangeText={text => this.setState({email: text})} underlineColorAndroid='black'/>
        <TextInput style={input} secureTextEntry={true} placeholder="Password" onChangeText={text => this.setState({password: text})}  underlineColorAndroid='black'/>

        <Button title={"Login"} onPress = {() => this.checkLogin()} />
      </View>
    );
  }

}

export default Home

当我发送此请求时,我没有收到任何响应,并在 Postman 上检查了响应,它以无效的 csrf 令牌和 403 错误的形式出现。最初在我的 Web 应用程序中登录时,表单包含一个 CSRF 令牌,其传递如下所示:

<input type = "hidden" name="_csrf" value="{{ csrfToken }}">

如何在 React Native App 上复制它?我尝试在网上搜索,但是找不到任何讨论的此类方法。

标签: react-nativecsrf

解决方案


您可以 1. 在请求标头中添加 CSRF 令牌或 2. 在后端禁用 CSRF。

export const login = (user) => {
  fetch('http://localhost:3000/api/session', {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': token
    },
    body: JSON.stringify({user})
  })
  // promise handling
}

推荐阅读