简体   繁体   English

反应原生的Google服务帐户身份验证

[英]Google service account authentication from react native

I'd like to use service account authentication within my react native app, in order to let people update a spreadsheet without the need for them to log into their google account. 我想在我的本机应用程序中使用服务帐户身份验证,以便让人们更新电子表格而无需他们登录到他们的Google帐户。

I'm pretty lost on how to do it, since all frontend code I see is related to traditional oauth2 login. 我很失落如何去做,因为我看到的所有前端代码都与传统的oauth2登录有关。

Any idea? 任何想法?

I finally dropped the idea of service account and used client oauth. 我终于放弃了服务帐户的想法并使用了客户端oauth。

I relied on the following React Native library : https://github.com/joonhocho/react-native-google-sign-in 我依赖以下React Native库: https//github.com/joonhocho/react-native-google-sign-in

Here is my authentication service (simplified, redux + redux thunk based): 这是我的身份验证服务(简化,基于redux + redux thunk):

// <project_folder>/src/services/auth.js
import GoogleSignIn from 'react-native-google-sign-in';
import { store } from '../store';
import auth from '../actions/auth';

export default () => {
    GoogleSignIn.configure({
        // https://developers.google.com/identity/protocols/googlescopes
        scopes: ['https://www.googleapis.com/auth/spreadsheets'],
        clientID: 'XXXXXXXXXXXXXXXXX.apps.googleusercontent.com',
    }).then(() => {
        GoogleSignIn.signInPromise().then((user) => {
            store.dispatch(auth(user.accessToken));
        }).catch((err) => {
            console.log(err);
        });
    }).catch((err) => {
        console.log(err);
    });
};

So then I have the user.accessToken in my redux store and can use it elsewhere to create REST requests to the google sheets API. 那么我在我的redux商店中有user.accessToken ,可以在其他地方使用它来创建对google工作表API的REST请求。

Here is a simple example of a component that handles the auth and then retrieves some data from the sheet: 下面是一个处理auth的组件的简单示例,然后从工作表中检索一些数据:

// <project_folder>/src/main.js
import React, { Component } from 'react';
import {
    ActivityIndicator,
    Text,
    View,
    StyleSheet,
} from 'react-native';
import { connect } from 'react-redux';
import auth from './services/auth';
import Sheet from './services/sheet';

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
});

const sheetId = 'XX-XXXXXX_XXX_XXXXXXXXXXXXXXXXXXXXXX';


class Main extends Component {
    constructor(props) {
        super(props);
        this.state = {
            animating: true,
        };
    }

    componentDidMount() {
        auth();
    }

    componentWillUpdate(nextProps) {
        if (this.props.token !== nextProps.token) this.setState({ animating: false });
    }

    componentDidUpdate(nextProps) {
        this.sheet = new Sheet(id, this.props.token);
        this.sheet.getDoc();
    }

    render() {
        return (
            <View style={styles.container}>
                <ActivityIndicator
                    animating={this.state.animating}
                    style={{ height: 80 }}
                    size="large"
                />
                {!this.state.animating &&
                    <Text>
                        {this.props.name}
                    </Text>
                }
            </View>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        token: state.auth.get('token'),
        name: state.sheet.get('name'),
    };
};

export default connect(mapStateToProps)(Main);

And here is a basic service to read/write a sheet: 这是一个读/写表单的基本服务:

// <project_folder>/services/sheet.js
import { store } from '../store';
import {
    nameGet,
    valueGet,
    valuePost,
}
from '../actions/sheet';

class Sheet {
    constructor(id, token) {
        this.id = id;
        this.token = token;
        this.endPoint = `https://sheets.googleapis.com/v4/spreadsheets/${this.id}`;
    }

    getDoc() {
        fetch(`${this.endPoint}?access_token=${this.token}`).then((response) => {
            response.json().then((data) => {
                console.log(data);
                store.dispatch(nameGet(data.properties.title));
            });
        });
    }

    getCell(sheet, cell) {
        const range = `${sheet}!${cell}`;
        fetch(`${this.endPoint}/values/${range}?access_token=${this.token}`)
        .then((response) => {
            response.json()
            .then((data) => {
                console.log(data);
                store.dispatch(valueGet(data.values[0][0]));
            })
            .catch((err) => {
                console.log(err);
            });
        })
        .catch((err) => {
            console.log(err);
        });
    }


    writeCell(sheet, cell, value) {
        const range = `${sheet}!${cell}`;
        const body = JSON.stringify({ values: [[value]] });
        fetch(
            `${this.endPoint}/values/${range}?valueInputOption=USER_ENTERED&access_token=${this.token}`,
            {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body,
            }
        )
        .then((response) => {
            response.json()
            .then((data) => {
                console.log(data);
                store.dispatch(valuePost('OK'));
            })
            .catch((err) => {
                console.log(err);
            });
        })
        .catch((err) => {
            console.log(err);
        });
    }
}

export default Sheet;

If there is a better way to do, please let me know. 如果有更好的方法,请告诉我。

I have no fully idea about this but yes if you can set the sheet permission as public and access from your application it will not ask you authentication. 我对此并不完全了解,但是如果您可以将工作表权限设置为公共权限并从您的应用程序访问它,则不会要求您进行身份验证。

also you may use below link may help more technical Google Sheets API v4 您也可以使用下面的链接来帮助更多技术Google表格API v4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在使用 google 身份验证的 google play 商店中发布 react native 应用程序 - Publish a react native app in the google play store that is using google authentication 无法使用 react-native 应用程序在 android 模拟器上登录 Google 帐户 - Could not sign in Google account on android emulator with react-native app 无法使用 React Native 和 Firebase 进行 Google OAuth 身份验证 - Unable to get Google OAuth authentication working with React Native and Firebase 使用 Firebase 身份验证从 Google 帐户注销 - Sign out from Google Account using Firebase Authentication React native - 从后台服务启动活动 - React native - Start activity from background service 在React Native中从Web服务填充ListView - Populate ListView from web service in React Native 使用Google帐户进行安全的Android身份验证 - Secure Android authentication with Google Account 从Android应用中作为Google云端存储的服务帐户进行身份验证 - Authenticate as a service account from Android app for Google Cloud Storage React Native 中的后台服务 - Background service in React Native Firebase自定义身份验证和服务帐户中的问题 - Issue In Firebase Custom Authentication And Service Account
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM