Lesson 56 of 60 – Authentication in React Native
93%

Authentication in React Native

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.

Note: Authentication is different from authorization. Authentication answers "Who are you?", while authorization determines "What are you allowed to access?"

1. What is Authentication?

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

2. Why is Authentication Important?

Authentication allows an application to provide personalized and account-based features.

  • User registration
  • User login
  • User logout
  • Profile management
  • Private application screens
  • User-specific data
  • Session management

3. Authentication vs Authorization

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.

4. Common Authentication Flow

Open App
   ↓
Login Screen
   ↓
Enter Credentials
   ↓
Send Request to API
   ↓
Server Checks Credentials
   ↓
Authentication Result
   ↓
Login Success?
   /       \
 Yes       No
  ↓         ↓
Home      Error
Screen    Message

5. Creating a Login Screen

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

6. Managing Email State

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

7. Managing Password State

const [password, setPassword] =
    useState("");

<TextInput
    value={password}
    onChangeText={setPassword}
    placeholder="Password"
    secureTextEntry
/>

The secureTextEntry property hides password characters in the user interface.

8. Validating Login Fields

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.

9. Sending Login Data to an API

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
        })
    }
);

10. Reading the Authentication Response

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.

11. Handling Successful Login

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

}

12. Handling Login Errors

If authentication fails, the application should display a clear error message.

if (!response.ok) {

    setError(
        "Invalid email or password"
    );

    return;

}

13. Creating an Authentication State

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.

14. Conditional Authentication UI

return (

    isLoggedIn
        ? <HomeScreen />
        : <LoginScreen />

);

When the authentication state changes, React can render the appropriate interface.

15. Creating a Logout Function

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.

16. Authentication with Navigation

Authentication is commonly combined with React Navigation.

if (isLoggedIn) {

    return <AppNavigator />;

}

return <AuthNavigator />;

This separates screens used before login from screens available after authentication.

17. Authentication and Loading State

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.

18. Authentication with AsyncStorage

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.

Security: Do not store passwords, private keys, or other sensitive secrets in ordinary AsyncStorage.

19. Token-Based Authentication

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.

20. Sending an Authentication Token

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.

21. Authentication Context

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.

22. Creating an Auth Provider

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.

23. Registration Flow

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.

24. Password Visibility

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.

25. Authentication with Axios

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.

26. Common Authentication Mistakes

  • Storing passwords in local storage.
  • Relying only on client-side validation.
  • Using HTTP instead of HTTPS for production authentication requests.
  • Ignoring authentication errors.
  • Showing protected screens before authentication is checked.
  • Forgetting to handle logout.
  • Hard-coding sensitive credentials inside the application.
  • Not handling expired sessions or tokens.
  • Keeping authentication logic scattered throughout the application.

27. Complete Basic Authentication Example

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>

    );

}

28. Authentication Best Practices

  • Use HTTPS for authentication APIs.
  • Validate input on both client and server.
  • Never store passwords in AsyncStorage.
  • Use an appropriate secure mechanism for sensitive credentials.
  • Keep authentication state centralized.
  • Handle loading and error states.
  • Protect authenticated screens through navigation logic.
  • Handle logout correctly.
  • Handle expired or invalid sessions.
  • Keep authentication code separate from presentation code where practical.

29. Important Authentication Concepts

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

30. Complete Authentication Workflow

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.

📌 Key Points

  • Authentication verifies a user's identity.
  • Login and registration are common authentication flows.
  • Authentication is normally connected to a backend API.
  • Use React state to manage authentication-related UI state.
  • Use loading states while checking authentication.
  • Authentication can be combined with React Navigation.
  • Protected screens should only be available according to the application's authentication state.
  • Tokens may be used by APIs to identify authenticated sessions.
  • Do not store passwords in ordinary AsyncStorage.
  • Use HTTPS for production authentication requests.
  • Authentication and authorization are different concepts.
  • Centralizing authentication logic can make an application easier to maintain.

🧠 Quick Quiz

Question: What is the main purpose of authentication?