Keeping User Logged In After Refresh/using Refresh Token With Google Oauth2 In React App
I’m building a React app where a key part of the functionality is a user can sign into their Google account and then access a feed of their most recent Google Drive/Docs mentions
Solution 1:
If you are using the client lib (the gapi api) there is no need for a refresh token... Once logged in it should persist across sessions and refreshes... The issue is the code...
1) Include this in your index.html
in the head
section:
<scriptsrc="https://apis.google.com/js/api.js"></script>
2) Here is a component that will handle auth using the gapi
lib and render a button conditionally (The code is self-explanatory but if you have a question just ask...)
importReactfrom'react';
classGoogleAuthextendsReact.Component {
state = { isSignedIn: null };
componentDidMount() {
window.gapi.load('client:auth2', () => {
window.gapi.client
.init({
clientId: '<your client id here...>',
scope: 'email', // and whatever else passed as a string...
})
.then(() => {
this.auth = window.gapi.auth2.getAuthInstance();
this.handleAuthChange();
this.auth.isSignedIn.listen(this.handleAuthChange);
});
});
}
handleAuthChange = () => {
this.setState({ isSignedIn: this.auth.isSignedIn.get() });
};
handleSignIn = () => {
this.auth.signIn();
};
handleSignOut = () => {
this.auth.signOut();
};
renderAuthButton() {
if (this.state.isSignedIn === null) {
returnnull;
} elseif (this.state.isSignedIn) {
return<buttononClick={this.handleSignOut}>Sign Out</button>;
} else {
return<buttononClick={this.handleSignIn}>Sign in with Google</button>;
}
}
render() {
return<div>{this.renderAuthButton()}</div>;
}
}
exportdefaultGoogleAuth;
Now you can simply use this component/button anywhere in your app... Meaning if you have a Navigation component simply import it there and use it as a button login / log out...
Post a Comment for "Keeping User Logged In After Refresh/using Refresh Token With Google Oauth2 In React App"