如何在React Native中使用API​​进行登录身份验证?

时间:2019-03-11 07:23:55

标签: api react-native-android

我有一个用于输入电子邮件和密码的字段,当我单击登录按钮时,我正在调用一种从后端获取用户的方法,如果响应成功,则应该可以导航至下一页。我怎么做?我有一个可以在Postman中正常工作的api,如何将api与UI连接并存储响应数据?在下面的代码中,我附加了我在代码中使用的api的响应图像

enter image description here

  import React from 'react';
    import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
    import PresentationalComponent from './PresentationalComponent'

    export default class App extends React.Component {
       constructor(){
           super();
           this.state = {
            email: '',
            password: '',
            result: false,
           }
       }

       updateState = () => {
          this.setState({ myState: 'The state is updated' })
       }

       _userLogin() {
         var email = this.state.username;
         var password = this.state.password;
         if (email && password) { // if validation fails, value will be null
           fetch("http://localhost:5000/api/login", {
             method: "POST",
             headers: {
               'Accept': 'application/json',
               'Content-Type': 'application/json'
             },
             body: JSON.stringify({
               username: email,
               password: password,
             })
           })
           .then((response) => response.json())
           .then((responseData) => {
             console.log(responseData);
             AlertIOS.alert(
               "Login Success!",
               "Click the button to get a Chuck Norris quote!"
             ),
             this._onValueChange(STORAGE_KEY, responseData.id_token)
           })
           .done();
           renderResults();
         }
       }

       renderResults = () => {
           if(responseData){
                this.setState({
                    result: true
                })
           }
       }

       handleEmail = (text) => {
             this.setState({ email: text })
       }

       handlePassword = (text) => {
             this.setState({ password: text })
       }

       render() {
          return (
             <View>
                {this.state.result ?
                     <PresentationalComponent/>
                     :
                     <View>
                        <TextInput
                          underlineColorAndroid = "transparent"
                          placeholder = "Email"
                          placeholderTextColor = "#9a73ef"
                          autoCapitalize = "none"
                          onChangeText = {this.handleEmail}
                        />
                        <TextInput
                           underlineColorAndroid = "transparent"
                           placeholder = "Password"
                           placeholderTextColor = "#9a73ef"
                           autoCapitalize = "none"
                           onChangeText = {this.handlePassword}
                        />
                        <Button
                             onPress={this._userLogin}
                             title="Learn More"
                             color="#841584"
                             accessibilityLabel="Learn more about this purple button"
                         />
                     </View>
                }
             </View>
          );
       }
    }

2 个答案:

答案 0 :(得分:0)

如果您使用反应导航,这很简单

if (response.status == "200") 
{
this.props.navigation.navigate(" ") //Add the page name in quote 
}

答案 1 :(得分:0)

我发现this article可能会对您有所帮助。

建议使用两个令牌-查看当前的API响应,我看不到任何令牌-重要的是要了解令牌和ID是两个不同的概念-您可能希望在登录过程中生成令牌。这些字符串可让服务器确保客户端已通过身份验证。

建议的实现,从开始到文章(略有简化):

  1. 用户登录时,服务器会生成刷新令牌,并将其包含在响应中,以便应用程序可以保存它。
  2. 客户端可以使用刷新令牌来获取访问令牌(也由服务器生成,但出于安全原因一小时后会过期)
  3. 客户端将每个请求的访问令牌发送到标头Authorization
  4. 中的受保护路由
  5. 服务器在处理请求之前先验证访问令牌

例如,用户在一天后打开该应用程序时,应从步骤2开始继续获取新的访问令牌。

用户注销后,应用程序应请求撤销两个令牌,以使其不再可用。