簡體   English   中英

反應原生的Google服務帳戶身份驗證

[英]Google service account authentication from react native

我想在我的本機應用程序中使用服務帳戶身份驗證,以便讓人們更新電子表格而無需他們登錄到他們的Google帳戶。

我很失落如何去做,因為我看到的所有前端代碼都與傳統的oauth2登錄有關。

任何想法?

我終於放棄了服務帳戶的想法並使用了客戶端oauth。

我依賴以下React Native庫: https//github.com/joonhocho/react-native-google-sign-in

這是我的身份驗證服務(簡化,基於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);
    });
};

那么我在我的redux商店中有user.accessToken ,可以在其他地方使用它來創建對google工作表API的REST請求。

下面是一個處理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);

這是一個讀/寫表單的基本服務:

// <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;

如果有更好的方法,請告訴我。

我對此並不完全了解,但是如果您可以將工作表權限設置為公共權限並從您的應用程序訪問它,則不會要求您進行身份驗證。

您也可以使用下面的鏈接來幫助更多技術Google表格API v4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM