Updated April 12, 2023
Introduction to React Native Authentication
In the current situation of cyber attacks, hackings etc user authentication is one of the most important aspects of any website or application. It comes with a solution for it which is called React Native Authentication. The biggest question right now is how to implement a real world user authentication properly and it has a solution for it. Most of the apps right now are using user authentication in a way to access the data the user is associated with or any other private content.
The flow for any user authentication looks like this:
- Firstly, the user has to open the app.
- The app will now load the authentication state.
- After the app has loaded the state, the user is presented with the authentication screen.
- After the user does their work on the app and signs out, the authentication state is cleared and once again the authentication screen comes up.
How does Authentication is done in React Native?
Given below is the way to import authorization in your application:
Code:
import { authorize } from 'react-native-app-auth';
constconfig = {
issuer: '<YOUR_ISSUER_URL>',
clientId: '<YOUR_CLIENT_ID>',
redirectUrl: '<YOUR_REDIRECT_URL>',
scopes: ['<YOUR_SCOPES_ARRAY>'],
};
const result = await authorize(config);
Examples
Given below are the examples mentioned:
Example #1
Basic React Native Authentication Page.
Components inside src folder:
- App.js
- Main.js
- Test.js
- Authentication.js
- index.js
a. App.js
import React, { Component } from "react";
import withFirebaseAuth from "react-auth-firebase"; import firebase from "./authentication";
import Home from "./Main"
class App extends Component { state = {
email: `[email protected]`, password: `welcome`
};
render() {
const{
signInWithEmail,
signUpWithEmail,
signInWithGoogle,
signInWithFacebook,
signInWithGithub,
signInWithTwitter,
googleAccessToken,
facebookAccessToken,
githubAccessToken,
twitterAccessToken,
twitterSecret,
user,
error,
signOut
} = this.props;
const{ password
, email } = this.state; if (user) {
return <Home user={user} error={error} signOut={signOut} />;
}
return (
<div>
<form onSubmit={e =>e.preventDefault()}>
<input
type="text"
placeholder="Enter Email Address"
onChange={e =>this.setState({ email: e.target.value })}
/>{" "}
<br/>
<input
type="password" placeholder="Enter Password"
onChange={e =>this.setState({ password: e.target.value })}
/>
<br />
{!user&& (
<button type="submit"
onClick={() =>signInWithEmail(email, password)}
>
Log In
</button>
)}
</form>
<form onSubmit={e =>e.preventDefault()}>
<input
type="text" placeholder="Email" onChange={e =>
this.setState({
email: e.target.value
})
}
value={email}
/>{" "}
<br/>
<input
type="password" placeholder="Welcome"
onChange={e =>this.setState({ password: e.target.value })} value={password}
/>{" "}
<br />
<button type="submit"
onClick={() =>signUpWithEmail(email, password)}
>
Create Account
</button>
</form>
<br />
<button onClick={signInWithGoogle}>Login with Google Account</button><br />
<button onClick={signInWithFacebook}>Login with Facebook Account</button>{" "}
<br />
<button onClick={signInWithGithub}>Login with Github Account</button><br/>
<button onClick={signInWithTwitter}>Login with Twitter Account</button><br/>
</div>
);
}
}
constauthConfig = { email: {
verifyOnSignup: false, saveUserInDatabase: true
},
google: { returnAccessToken: true, saveUserInDatabase: true
},
facebook: { redirect: true,
returnAccessToken: true, saveUserInDatabase: true
},
github: { returnAccessToken: true, saveUserInDatabase: true
},
twitter: { returnAccessToken: true,
returnSecret: true, saveUserInDatabase: true
}
};
export default withFirebaseAuth(App, firebase, authConfig);
b. Main.js
import React from "react";
import withAuthFirebase from "react-auth-firebase"; import firebase from "./authentication";
import App from "./App";
const Home = props =>{ console.log(props);
const{ user, signOut, error } = props; if (!user) {
return <App />;
}
return (
<div>
<h1>Hello</h1>
<button onClick={signOut}>Sign Out</button>
{user ?<pre>{JSON.stringify(user, null, 2)}</pre> : null}
{error ?<h1>{error.message}</h1> : null}
</div>
);
};
export default Home;
c. Test.js
import React from "react";
export default () => (
<div>
<h1>Welcome to My Application</h1>
</div>
);
d. Authentication.js
import firebase from "firebase";
export constconfig = {
apiKey: "AIzaSyDS1uhpHa0svJOtqSay67WAtT4Cbn9qLls",
authDomain: "react-auth-firebase-593c8.firebaseapp.com",
databaseURL: "https://react-auth-firebase-593c8.firebaseio.com", projectId: "react-auth-firebase-593c8",
storageBucket: "react-auth-firebase-593c8.appspot.com", messagingSenderId: "992705895311"
};
firebase.initializeApp(config);
export default firebase;
e. index.js
import React from "react";
import { render } from "react-dom"; import App from "./App";
import Home from "./Main";
const Index = () => (
<div>
<App />
</div>
);
render(<Index />, document.getElementById("root"));
Output:
Example #2
Page with GoogleAuthentication.
Components inside src folder:
- Componentfolder
- index.js
- style.css
Components inside Component folder:
- App.js
- button.css
a. App.js
import React from "react";
import "./button.css";
class App extends React.Component {
state = { isSignedIn: null, userGoodName: "" };
componentDidMount() { window.gapi.load("client: auth2", () => {
window.gapi.client
.init({ clientId:
"403650961654-
vdnsejt1smk0c91g2a8vja1751tutnni.apps.googleusercontent.com", scope: "email"
})
.then(() => {
this.auth = window.gapi.auth2.getAuthInstance();
this.setState({ isSignedIn: this.auth.isSignedIn.get() }); console.log(this.state.isSignedIn);
constuserInitial = this.auth.currentUser.get().Qt.Ad; this.setState({ userGoodName: userInitial }); console.log(this.state.userGoodName);
this.auth.isSignedIn.listen(this.onAuthChange);
});
});
}
onAuthChange = () => {
this.setState({ isSignedIn: this.auth.isSignedIn.get() }); this.setState({ userGoodName: this.auth.currentUser.get() });
};
onSignInClick = () =>{ this.auth.signIn();
};
onSignOutClick = () =>{ this.auth.signOut();
};
renderAuthButton() {
if (this.state.isSignedIn === null) {
return <div className="ui text loader">PLEASE WAIT! PAGE IS LOADING
</div>;
} else if (this.state.isSignedIn) { return (
<div>
<button className="g-button" onClick={this.onSignOutClick}>
<img
className="g-logo"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G% 22_Logo.svg/157px-Google_%22G%22_Logo.svg.png"
alt="Google Logo"
/>
<p className="g-text">Log Out</p>
</button>
<br />
<h3>Hello {this.state.userGoodName}</h3>
</div>
);
} else { return (
<div>
<button className="g-button" onClick={this.onSignInClick}>
<img
className="g-logo"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G% 22_Logo.svg/157px-Google_%22G%22_Logo.svg.png"
alt="Google Logo"
/>
<p className="g-text">Sign in with your Google Account</p>
</button>
<br />
<h3>Hello! Please Sign in to Access the content of Our Website</h3>
</div>
);
}
}
render() { return (
<div className="g_body">
<h3>{this.renderAuthButton()}</h3>
</div>
);
}
}
export default App;
b. button.css
@import url("https://fonts.googleapis.com/css?family=Roboto&display=swap");
* {
margin: 1;
padding: 1;
font-family: roboto;
}
html, body, #root {
height: 99%;
align-items: center; justify-content: center; text-align: center;
}
.g_body { height: 99%; display: flex;
align-items: center; justify-content: center; text-align: center;
}
.g-button {
border: 1px solid #d5ff7a; background: #60bee0; display: flex;
align-items: center; justify-content: center; text-align: center; cursor: pointer;
}
.g-logo { width: 22px; height: 22px;
padding: 9px 11px; background:#ffffff;
}
.g-text {
font-size: 17px; padding: 9px 11px; color: #baffe0;
font-family: sans-serif; text-align: center;
}
c. index.js
import React from "react";
import ReactDOM from "react-dom"; import App from "./Component/App";
ReactDOM.render(<App />, document.querySelector("#root"));
d. style.css
.App {
font-family: roboto; text-align: center;
}
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
}
Output:
Conclusion
Here we saw about what Authentication is and why it is used. We have developed various pages for it-based applications which have various login options like Login with Google, Facebook, Twitter, etc. It is a crucial part of an application and it can be easily done.
Recommended Articles
This is a guide to React Native Authentication. Here we discuss the introduction and how authentication is done with programming examples. You may also have a look at the following articles to learn more –