Summary - Authentication
- React Native course
- Advanced
- Lesson 48/83
- 5 min
Combine context, JWT and protected routes to write an auth flow.
Summary - Authentication
In this group you learned auth context, login, JWT, protected routes and logout. AuthContext carries the central state; Provider exposes it to the whole app. Login updates the context with auth.login({ user, token }).
The token is written to SecureStore and sent with an Authorization: Bearer header on requests. Protected screens redirect to login with if (!user). Logout deletes the token and calls setUser(null). Now we will combine these into a working auth skeleton.
Practice Summary - Auth provider skeleton
Complete the AuthProvider component. Define user state with useState(null). The login function should call setUser(data). Return an AuthContext.Provider with value={{ user, login }}.
Starter code
import React, { createContext, useState } from 'react';
export const AuthContext = createContext(null);
export function AuthProvider({ children }) {
// user state, login function, and Provider return
}Sample solution
import React, { createContext, useState } from 'react';
export const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
function login(data) {
setUser(data);
}
return (
<AuthContext.Provider value={{ user, login }}>
{children}
</AuthContext.Provider>
);
}Practice Summary - Full logout
Complete the logout function. Delete the token with await SecureStore.deleteItemAsync('token'). Reset the context with setUser(null). The function must be async.
Starter code
import * as SecureStore from 'expo-secure-store';
export function makeFullLogout(setUser) {
// write the logout function
}Sample solution
import * as SecureStore from 'expo-secure-store';
export function makeFullLogout(setUser) {
async function logout() {
await SecureStore.deleteItemAsync('token');
setUser(null);
}
return { logout };
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the flow parts
| Term | Meaning |
|---|---|
createContext |
Creates the AuthContext |
login({ user, token }) |
Updates the context |
Bearer ${token} |
Authorization header |
deleteItemAsync('token') |
Deletes on logout |
2 Write the Bearer header
headers: { Authorization: `Bearer ${____}` }
headers: { Authorization: `Bearer ${token}` }
Explanation: The token variable goes into the header.