Authentication is the process of verifying the identity of a user. In a React Native application, authentication is commonly used to allow users to register, log in, log out, and access application features based on their authentication status.
A typical authentication system communicates with a backend API. The React Native application sends login information to the server, receives an authentication result, and then controls the application flow.
Authentication verifies whether a user is who they claim to be.
For example, a student may enter an email address and password. The server checks those credentials and returns an appropriate result.
Email
+
Password
↓
Authentication Server
↓
Valid / Invalid
Authentication allows an application to provide personalized and account-based features.
| Concept | Meaning |
|---|---|
| Authentication | Verifies the identity of a user |
| Authorization | Determines what the authenticated user can access |
For example, logging into an education application is authentication. Checking whether that user can access an admin screen is authorization.
Open App
↓
Login Screen
↓
Enter Credentials
↓
Send Request to API
↓
Server Checks Credentials
↓
Authentication Result
↓
Login Success?
/ \
Yes No
↓ ↓
Home Error
Screen Message
A login screen normally contains fields for user credentials and a button to submit them.
<TextInput
placeholder="Email"
/>
<TextInput
placeholder="Password"
secureTextEntry
/>
<Button
title="Login"
onPress={handleLogin}
/>
React state can be used to store the value entered in the email field.
const [email, setEmail] =
useState("");
<TextInput
value={email}
onChangeText={setEmail}
placeholder="Email"
/>
const [password, setPassword] =
useState("");
<TextInput
value={password}
onChangeText={setPassword}
placeholder="Password"
secureTextEntry
/>
The secureTextEntry property hides password characters in
the user interface.
Before sending a login request, basic validation can check whether the required fields have been entered.
if (!email || !password) {
setError("Please enter email and password");
return;
}
Client-side validation improves the user experience, but the server must also validate authentication requests.
The login form can send credentials to a backend API.
const response = await fetch(
"https://example.com/api/login",
{
method: "POST",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify({
email: email,
password: password
})
}
);
After receiving a response, the application can convert the response body into JSON.
const data =
await response.json();
console.log(data);
The exact response format depends on the backend API.
When the server confirms successful authentication, the application can update its authentication state and navigate to the appropriate screen.
if (response.ok) {
console.log(
"Login successful"
);
// Update authentication state
}
If authentication fails, the application should display a clear error message.
if (!response.ok) {
setError(
"Invalid email or password"
);
return;
}
A root component can maintain whether the user is authenticated.
const [isLoggedIn, setIsLoggedIn] =
useState(false);
The application can use this state to decide which part of the application should be displayed.
return (
isLoggedIn
? <HomeScreen />
: <LoginScreen />
);
When the authentication state changes, React can render the appropriate interface.
A logout function can clear the application's authentication state.
function handleLogout() {
setIsLoggedIn(false);
}
In a real application, logout may also involve clearing application session data and invalidating a server-side session or token when appropriate.
Authentication is commonly combined with React Navigation.
if (isLoggedIn) {
return <AppNavigator />;
}
return <AuthNavigator />;
This separates screens used before login from screens available after authentication.
When an application starts, it may need to check whether an existing session is still valid. A loading state prevents the application from showing the wrong screen while this check is running.
const [loading, setLoading] =
useState(true);
After the authentication check completes, the application can set
loading to false.
AsyncStorage can be used for appropriate non-sensitive local session information, such as a user identifier or application-specific session flag.
await AsyncStorage.setItem(
"userId",
"101"
);
On application startup, this information can be read to help restore the application state.
Many modern applications use token-based authentication. After successful login, the server may return an access token or another session credential.
Login Request
↓
Server
↓
Authentication Success
↓
Token
↓
React Native App
The exact token mechanism depends on the backend authentication system.
When an API requires a bearer access token, the application can include it in the request header.
const response = await fetch(
"https://example.com/api/profile",
{
headers: {
Authorization:
`Bearer ${token}`
}
}
);
The backend verifies the token before returning protected data.
When many screens need authentication information, React Context can provide a centralized authentication state.
const AuthContext =
createContext(null);
An authentication provider can expose values such as the current user, login function, logout function, and loading state.
function AuthProvider({ children }) {
const [user, setUser] =
useState(null);
const login = (userData) => {
setUser(userData);
};
const logout = () => {
setUser(null);
};
return (
<AuthContext.Provider
value={{
user,
login,
logout
}}
>
{children}
</AuthContext.Provider>
);
}
This pattern allows different components to access authentication state without passing it through every component manually.
Authentication systems commonly include user registration.
Registration Screen
↓
Name
Email
Password
↓
POST Request
↓
Backend
↓
Account Created
↓
Login / Application
Registration validation and password handling should be performed securely on the backend.
A password field can provide a visibility option so users can temporarily see what they typed.
const [showPassword, setShowPassword] =
useState(false);
<TextInput
secureTextEntry={!showPassword}
placeholder="Password"
/>
A button or icon can change the value of showPassword.
Axios can also be used to send authentication requests.
const response = await axios.post(
"https://example.com/api/login",
{
email,
password
}
);
console.log(response.data);
Axios provides convenient request and response handling, while the backend remains responsible for validating credentials.
import React, {
useState
} from "react";
import {
View,
Text,
TextInput,
Button
} from "react-native";
export default function LoginScreen({
onLogin
}) {
const [email, setEmail] =
useState("");
const [password, setPassword] =
useState("");
const [error, setError] =
useState("");
async function handleLogin() {
setError("");
if (!email || !password) {
setError(
"Enter email and password"
);
return;
}
try {
const response = await fetch(
"https://example.com/api/login",
{
method: "POST",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify({
email,
password
})
}
);
const data =
await response.json();
if (!response.ok) {
setError(
data.message ||
"Login failed"
);
return;
}
onLogin(data);
} catch (error) {
setError(
"Network error"
);
}
}
return (
<View>
<Text>Login</Text>
<TextInput
placeholder="Email"
value={email}
onChangeText={setEmail}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
{error
? <Text>{error}</Text>
: null
}
<Button
title="Login"
onPress={handleLogin}
/>
</View>
);
}
| Concept | Purpose |
|---|---|
| Login | Verifies user credentials |
| Registration | Creates a user account |
| Logout | Ends the current application session |
| Authentication State | Represents whether a user is authenticated |
| Access Token | Credential used by an API to identify an authenticated session |
| Protected Screen | Screen intended for authenticated users |
| Authorization | Controls what an authenticated user can access |
React Native Application
↓
Login Screen
↓
Enter Email + Password
↓
API Request
↓
Backend
↓
Verify Credentials
↓
Authentication Result
/ \
Success Failed
↓ ↓
Session/Token Error
↓
Update Auth State
↓
Protected Navigation
↓
Application Screens
↓
Logout
↓
Clear Session State
Authentication is a fundamental part of many mobile applications. React Native handles the user interface and application state, while a backend service normally performs the actual credential verification and account management.
Question: What is the main purpose of authentication?