Set up a Front end authentification
Building Secure Web Experiences: Mastering Front-End Authentication and it's difference from Authorization
1- Introduction:
Front-end authentication is crucial for securing your web application. In this article, I'll show you how to implement it using ReactJS. Don't worry if you're not familiar with React or authentication; I'll explain everything in detail. By the end, you'll be able to create a secure login and admin page for your app.
2- What is authentification
Imagine you are at home, and you open the door with your keys. When you enter, your kids are happy to see you π₯³. This is because they recognize you and know you have the right to be there.
Now, imagine a burglar tries to break into your house without a key, perhaps by breaking the lock π³. However, you've already prepared for this situation. You've taught your kids to hide everything or alert the authorities if they sense a burglar coming. This way, the burglar won't be able to harm you or steal anything because you planned ahead.
In this analogy:
Your house is like a website.
The keys are your login credentials (username and password).
You are a token that verifies your identity.
When you use your keys to open the door, it's like entering your login credentials to access the website. The kids (representing the website) see you (the token) and recognize that you have the right to be there, allowing you access to all the features and information.
On the other hand, if a burglar (an unauthorized user) tries to enter, the kids (the website) won't recognize them because they don't have the proper keys (login credentials). The kids will either hide everything (deny access to sensitive information) or take action to protect the house (redirect to the login page).
When setting up front-end authentication, we primarily work with two methods:
Login Credentials: Users provide their username and password to verify their identity.
Token-Based Authentication: Once verified, the system issues a token to the user. This token is used for subsequent requests to ensure the user is still authenticated.
This ensures that only authorized users can access the website's resources, maintaining security and protecting against unauthorized access.
3- Implement front-end authentication :
Imagine you make a request to the following API: https://testApi.com/login
+ on success: {status: 200, message: 'logged in successfully', token: 'sdf389dxbf1sdz51fga65dfg74asdf' }
+ on failure: {status: 401, message: 'invalid credentials' }
On the front end, let's create two pages: a login page and an admin page. The admin page must be secure, allowing access only to authenticated users.
in src/pages/Login.js
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
const Login = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch('https://testApi.com/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await response.json();
if (response.status === 200) {
localStorage.setItem('token', data.token);
navigate('/admin');
} else {
alert(data.message);
}
} catch (error) {
console.error('Login error:', error);
}
};
return (
<div>
<h2>Login</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Username</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div>
<label>Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit">Login</button>
</form>
</div>
);
};
export default Login;
The login process is simple. It sends a request, and if successful, we store the token in local storage. Piece of cake! :)
in src/pages/Admin.js
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
const Admin = () => {
const navigate = useNavigate();
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
console.log('Token found:', token);
} else {
navigate('/login');
}
}, [navigate]);
const handleLogout = () => {
localStorage.removeItem('token');
navigate('/login');
};
return (
<div>
<h2>Admin Page</h2>
<button onClick={handleLogout}>Logout</button>
</div>
);
};
export default Admin;
In the Admin component, when it fully renders, the useEffect
function runs and checks if the token is in local storage. If not, it redirects you to the login page. If you want to make a POST request, always add the token in the headers.
Example: headers = { Accept: "application/json", Authorization: "Bearer <token>" }} ${token}, };
in src/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Login from './pages/Login';
import Admin from './pages/Admin';
const App = () => {
return (
<Router>
<Routes>
<Route path="/login" component={Login} />
<Route path="/admin" component={Admin} />
<Route path="/" component={Login} />
</Routes>
</Router>
);
};
export default App;
I work as a freelance software developer. I've got you covered if you need a web application, desktop application, automation solutions, or even SEO and design improvements for your existing page! ππ»β¨
Contact me at code-with-amine@gmail.com letβs build what youβre looking for π
6- Difference Between Authentication and Authorization:
π Many people confuse authentication and authorization, but they serve distinct purposes in web security.
Authentication is the process of verifying who a user is. For example, when you log in to a website, you enter your username and password. The system checks these credentials against its records to confirm your identity.
Authorization, on the other hand, determines what an authenticated user is allowed to do. Each user has specific roles and permissions. For instance, a pilot has the authorization to fly a plane, while a passenger does not. It's as simple as that. π
To further clarify:
Authentication: Proves you are who you say you are (like using keys to enter your house).
Authorization: Grants or denies access to certain resources or actions based on your identity (like having the permission to fly a plane if you're a pilot).
In the context of web applications:
Authentication: Logging in with a username and password.
Authorization: Checking if the logged-in user has permission to access certain pages or perform specific actions.
5- Summary:
In this article, we explored the concept of front-end authentication and implemented a simple authentication system using ReactJS. We created a login page that sends credentials to an API and stores a token upon successful login. We also set up an admin page that checks for the token and redirects to the login page if the token is missing. This ensures that only authenticated users can access the admin page.
Now that you've learned the basics of front-end authentication, try implementing it in your own projects. If you have any questions or feedback, feel free to leave a comment below. Happy coding!