Folder Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"axios": "^1.6.7",
"web-vitals": "^2.1.4"
},
Example: Below is an example of creating 5 simple steps for athutentication and authorization in MERN Stack.
CSS
/* App.css */ /* src/App.css */ body { font-family : 'Arial' , sans-serif ; background-color : #f4f4f4 ; margin : 0 ; padding : 0 ; } .container { max-width : 600px ; margin : 50px auto ; background-color : #fff ; padding : 20px ; border-radius: 8px ; box-shadow: 0 0 10px rgba( 0 , 0 , 0 , 0.1 ); } h 1 { text-align : center ; color : #333 ; } form { display : flex; flex- direction : column; } input { margin-bottom : 10px ; padding : 8px ; font-size : 16px ; border : 1px solid #ccc ; border-radius: 4px ; } button { background-color : #4caf50 ; color : #fff ; padding : 10px ; font-size : 16px ; border : none ; border-radius: 4px ; cursor : pointer ; } button:hover { background-color : #45a049 ; } p { margin-top : 20px ; font-size : 14px ; color : #333 ; } |
Javascript
//App.js import React, { useState } from 'react' ; import axios from 'axios' ; import './App.css' ; function App() { const [username, setUsername] = useState( '' ); const [email, setEmail] = useState( '' ); const [password, setPassword] = useState( '' ); const [loginEmail, setLoginEmail] = useState( '' ); const [loginPassword, setLoginPassword] = useState( '' ); const [token, setToken] = useState( '' ); const handleRegister = async () => { try { const response = await axios.post( 'http://localhost:5000/auth/register' , { username, email, password, }, { withCredentials: true } // Add this option ); console.log(response.data); } catch (error) { console.error(error.response.data.error); } }; const handleLogin = async () => { try { const response = await axios.post( 'http://localhost:5000/auth/login' , { email: loginEmail, password: loginPassword, }, { withCredentials: true } ); setToken(response.data.token); console.log( 'Login successful' ); } catch (error) { console.error(error.response.data.error); } }; const handleLogout = async () => { try { const response = await fetch( 'http://localhost:5000/auth/logout' , { method: 'POST' , credentials: 'include' , }); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } /* Clear any client-side authentication data (e.g., token stored in localStorage) */ localStorage.removeItem( 'token' ); console.log( "Logged out" ); // Redirect or update UI as needed after logout } catch (error) { console.error( 'Error during logout:' , error); } }; return ( <div> <h1>Authentication App</h1> <div> <h2>Register</h2> <input type= "text" placeholder= "Username" value={username} onChange={(e) => setUsername(e.target.value)} /> <input type= "email" placeholder= "Email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type= "password" placeholder= "Password" value={password} onChange={(e) => setPassword(e.target.value)} /> <button onClick={handleRegister}>Register</button> </div> <div> <h2>Login</h2> <input type= "email" placeholder= "Email" value={loginEmail} onChange={(e) => setLoginEmail(e.target.value)} /> <input type= "password" placeholder= "Password" value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)} /> <button onClick={handleLogin}>Login</button> </div> {token && <p>Token: {token}</p>} <button onClick={handleLogout}>Logout</button> </div> ); } export default App; |
Start your application using the following command in your terminal.
npm start
Output:
5 Simple Steps for Authentication and Authorization in MERN Stack
Implementing authentication and authorization in a MERN stack application is crucial for ensuring the security of your application and protecting sensitive data. Here’s an elaboration on the five simple steps you can take to achieve this:
Table of Content
- Implementing Authentication and Authorization in MERN App:
- How Authentication is done in MERN Stack ?
- How Authorization is done in MERN Stack:
- Steps to implement Authentication & Authorization in Backend: