Auth
Auth
What is authentication?
Authentication is the process of letting users signup/signin into websites via username /
password or using SSO (single sign on)
https://projects.100xdevs.com/pdf/Auth/auth-1 1/13
7/8/24, 11:32 PM DailyCode
Signin
Auth requests
https://projects.100xdevs.com/pdf/Auth/auth-1 2/13
7/8/24, 11:32 PM DailyCode
1. Session Management: Cookies allow websites to identify users and track their individual
session states across multiple pages or visits.
2. Personalization: Websites use cookies to personalize content and ads. For instance, cookies
might store information about a user's preferences, allowing the site to tailor content or
advertisements to those interests.
3. Tracking: Cookies can track users across websites, providing insights into browsing behavior.
This information can be used for analytics purposes, to improve website functionality, or for
advertising targeting.
4. Security: Secure cookies can be used to enhance the security of a website by ensuring that
the transmission of information is only done over an encrypted connection, helping to
prevent unauthorized access to user data.
1. Cookies are send with every request to the website (by the browser) (you don’t have to
explicitly add a header to the fetch call)
This point becomes super important in Next.js, we’ll see later why
💡 Ref - https://github.com/100xdevs-cohort-2/paytm/blob/complete-
solution/frontend/src/pages/SendMoney.jsx#L45
https://projects.100xdevs.com/pdf/Auth/auth-1 3/13
7/8/24, 11:32 PM DailyCode
Signup
Signin
https://projects.100xdevs.com/pdf/Auth/auth-1 4/13
7/8/24, 11:32 PM DailyCode
Auth endpoints
You don’t need to explicitly set the cookie header in the browser. It’s automatically set by the
browser in every request
Properties of cookies
Types of cookies
1. Persistent - Stay even if u close the window
Properties of cookies
HttpOnly - Can not be accessed by client side scripts
1. Strict
3. None
Ref - https://portswigger.net/web-security/csrf/bypassing-samesite-
restrictions#:~:text=SameSite is a browser security,leaks%2C and some CORS exploits.
https://projects.100xdevs.com/pdf/Auth/auth-1 5/13
7/8/24, 11:32 PM DailyCode
Domains - You can also specify what all domains should the cookie be sent from
CSRF attacks
Cross site request forgery attacks were super common because of cookies and hence the
SameSite attribute was introduced
SameSite: none
SameSite: Strict
https://projects.100xdevs.com/pdf/Auth/auth-1 6/13
7/8/24, 11:32 PM DailyCode
SameSite: Lax
https://projects.100xdevs.com/pdf/Auth/auth-1 7/13
7/8/24, 11:32 PM DailyCode
Copy
app.post("/logout", (req, res) => {
res.cookie("token", "ads");
res.json({
message: "Logged out!"
})
});
Copy
app.listen(3000);
Code - https://github.com/100xdevs-cohort-2/week-16-auth-1
Frontend in React
Initialize an empty react project
https://projects.100xdevs.com/pdf/Auth/auth-1 9/13
7/8/24, 11:32 PM DailyCode
return <div>
<input onChange={(e) => {
setUsername(e.target.value);
}} type="text" placeholder="username" />
<input onChange={(e) => {
setPassword(e.target.value);
}} type="password" placeholder="password" />
<button onClick={async () => {
await axios.post(`${BACKEND_URL}/signin`, {
username,
password
}, {
withCredentials: true,
});
alert("you are logged in")
}}>Submit</button>
</div>
}
useEffect(() => {
axios.get(`${BACKEND_URL}/user`, {
withCredentials: true,
})
.then(res => {
setUserData(res.data);
})
}, []);
return <div>
You're id is {userData?.userId}
<br /><br />
<button onClick={() => {
https://projects.100xdevs.com/pdf/Auth/auth-1 10/13
7/8/24, 11:32 PM DailyCode
axios.post(`${BACKEND_URL}/logout`, {}, {
withCredentials: true,
})
}}>Logout</button>
</div>
}
Add routing
function App() {
return (
<BrowserRouter>
<Routes>
<Route path={"/signup"} element={<Signup />} />
<Route path={"/signin"} element={<Signin />} />
<Route path={"/user"} element={<User />} />
</Routes>
</BrowserRouter>
)
}
Code - https://github.com/100xdevs-cohort-2/week-16-auth-1
<!DOCTYPE html> Co
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
https://projects.100xdevs.com/pdf/Auth/auth-1 11/13
7/8/24, 11:32 PM DailyCode
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<script>
try {
await axios.post(`/signin`, {
username,
password
});
alert("You are logged in");
} catch (error) {
console.error('Login failed:', error);
alert("Login failed");
}
});
document.getElementById('logoutButton').addEventListener('click', () => {
axios.post(`/logout`, {}, {
withCredentials: true,
}).then(() => {
console.log('Logged out successfully.');
}).catch(error => {
console.error('Logout failed:', error);
});
});
function fetchUserData() {
axios.get(`/user`, {
withCredentials: true,
}).then(response => {
const userData = response.data;
displayUserData(userData);
}).catch(error => {
console.error('Failed to fetch user data:', error);
});
}
function displayUserData(userData) {
const userDataDiv = document.getElementById('userData');
https://projects.100xdevs.com/pdf/Auth/auth-1 12/13
7/8/24, 11:32 PM DailyCode
</body>
</html>
app.use(cors()); Copy
Link - https://github.com/100xdevs-cohort-2/week-16-auth-1
https://projects.100xdevs.com/pdf/Auth/auth-1 13/13