首页 > 解决方案 > expo-google-app-auth 的 Android 问题

问题描述

我在Android. 它与IOS.

在 Android 中成功登录而不是将我重定向回我的应用程序LoggedInPage组件后,我再次进入LoginPage组件。我认为这是因为Android再次打开应用程序并且我失去了状态,所以我也失去了登录状态,我必须再次登录......

在IOS中,它只是让我LoggedInPage完美地重定向到组件..

import React, { useState } from "react";
import * as Google from "expo-google-app-auth";

import { StyleSheet, Text, View, Image, Button } from "react-native";

export default function App() {
  const [signedIn, setSignIn] = useState(false);
  const [name, setName] = useState("");
  const [photoUrl, setPhotoUrl] = useState("");

  signIn = async () => {
    try {
      console.log("Sign in 1");
      const result = await Google.logInAsync({
        androidClientId:
          “&lt;< android client id >>apps.googleusercontent.com",
        iosClientId:
          “&lt;< iOS client id >>.apps.googleusercontent.com",
        scopes: ["profile", "email"]
      });
      console.log("Sign in 2");

      console.log("Result: ", result);
      if (result.type === "success") {
        setSignIn(true);
        setName(result.user.name);
        setPhotoUrl(result.user.photoUrl);
        return result.accessToken;
      } else {
        return { cancelled: true };
      }
    } catch (e) {
      return { error: true };
    }
  };

  const LoginPage = () => {
    console.log("Inside LoginPage");
    return (
      <View>
        <Text style={styles.header}>Sign In With Google</Text>
        <Button title="Sign in with Google" onPress={() => signIn()} />
      </View>
    );
  };

  const LoggedInPage = () => {
    return (
      <View style={styles.container}>
        <Text style={styles.header}>Welcome:{name}</Text>
        <Image style={styles.image} source={{ uri: photoUrl }} />
      </View>
    );
  };

  console.log("SignedIn: ", signedIn);

  return (
    <View style={styles.container}>
      {signedIn ? <LoggedInPage /> : <LoginPage />}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  },
  header: {
    fontSize: 25
  },
  image: {
    marginTop: 15,
    width: 150,
    height: 150,
    borderColor: "rgba(0,0,0,0.2)",
    borderWidth: 3,
    borderRadius: 150
  }
});

任何想法/指导我应该如何在 Android 中修复我的应用程序?

标签: androidreactjsreact-nativeexpogoogle-oauth

解决方案


您需要添加一个redirectUrl:

const result = await Google.logInAsync({
        androidClientId:
          “&lt;< android client id >>apps.googleusercontent.com",
        iosClientId:
          “&lt;< iOS client id >>.apps.googleusercontent.com",
        scopes: ["profile", "email"],
        redirectUrl: "{Your Bundle ID (com.example.app)}:/oauth2redirect/google",
      });
    
    

推荐阅读