Using JWT (JSON Web Tokens) for authentication in a React frontend and a Yii2 backend is a common approach for securing your application. The decision to create a helper or a component largely depends on your architectural preferences and the complexity of your application. However, I can suggest a structured way to implement JWT authentication across both components.
General Structure
-
Backend (Yii2):
- JWT Library: Use a library like
lcobucci/jwt or firebase/php-jwt to encode and decode JWTs.
- User Authentication: Create an endpoint for authenticating users where you verify their credentials, and if valid, generate and return a JWT.
- Middleware: Implement middleware to verify JWTs on protected routes.
-
Frontend (React):
- Storage: Store the JWT in local storage or session storage when the user logs in, and send it with every request to protected endpoints.
- Context/State Management: Use React Context, Redux, or another state management library to handle the authentication state and user information across your app.
- API Helper: Create an API helper module for making API calls that automatically attaches the JWT to the request headers.
Implementation Steps
1. Backend (Yii2)
Step 1: Install JWT Library
composer require firebase/php-jwt
Step 2: User Authentication Endpoint
In your controller, create an action for user authentication:
use Firebase\JWT\JWT;
public function actionLogin()
{
$model = new LoginForm(); // Assume you have a LoginForm model
if ($model->load(Yii::$app->request->post()) && $model->login()) {
// User has successfully logged in
$user = $model->getUser();
$token = JWT::encode([
'id' => $user->id,
'exp' => time() + 3600, // Token will expire in 1 hour
], 'your_secret_key'); // Use a secure key
return ['token' => $token];
}
return [
'error' => 'Invalid login credentials',
];
}
Step 3: Middleware for JWT Verification
In your Yii2 configuration, set up a filter for routes that require authentication:
public function beforeAction($action)
{
if (in_array($action->id, ['protectedRoute'])) {
$headers = Yii::$app->request->headers;
$token = $headers->get('Authorization');
if ($token) {
try {
$decoded = JWT::decode(substr($token, 7), 'your_secret_key', ['HS256']);
// Set user identity or other logic
} catch (Exception $e) {
return $this->asJson(['error' => 'Unauthorized']);
}
} else {
return $this->asJson(['error' => 'Authorization header missing.']);
}
}
return parent::beforeAction($action);
}
2. Frontend (React)
Step 4: API Helper
Create a helper function to handle API calls.
// api.js
const apiUrl = 'http://your-backend-url/api';
export const apiCall = async (endpoint, method = 'GET', body = null) => {
const token = localStorage.getItem('token');
const headers = new Headers({
'Content-Type': 'application/json',
...(token && { 'Authorization': `Bearer ${token}` }),
});
const response = await fetch(`${apiUrl}/${endpoint}`, {
method,
headers,
body: body ? JSON.stringify(body) : null,
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
};
Step 5: Authentication Logic
Integrate the login function in your authentication context or state management.
// authContext.js
import React, { createContext, useContext, useState } from 'react';
import { apiCall } from './api';
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const login = async (credentials) => {
const data = await apiCall('login', 'POST', credentials);
localStorage.setItem('token', data.token);
setUser(data.user); // assuming user object is returned
};
const logout = () => {
localStorage.removeItem('token');
setUser(null);
};
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);
Conclusion
- Helpers: Great for encapsulating the API logic for making authenticated requests.
- Context/State Management: Separate Authentication state management makes it easier to handle user state across your app.
By following this structured approach, you can ensure a robust JWT authentication system for your React and Yii2 application.