Authentication
What is Authentication?
Authentication is the process of verifying the identity of a user, device, or other entity. It ensures that the party attempting to access a system is who they claim to be.
Common Methods
- Password‑Based: Traditional username & password verification.
- OAuth 2.0: Delegated authentication via third‑party providers (Google, GitHub, etc.).
- JWT (JSON Web Tokens): Stateless tokens that carry claims about the user.
- Multi‑Factor (MFA): Combines something you know with something you have.
Best Practices
- Always hash passwords with a strong algorithm (bcrypt, Argon2).
- Use HTTPS for all auth endpoints.
- Implement rate limiting and account lockout.
- Prefer short‑lived JWTs with refresh tokens.
- Store secrets securely (environment variables, vaults).
Login Form Example
<form id="loginForm">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<button type="submit">Sign In</button>
</form>
<script>
document.getElementById('loginForm').addEventListener('submit', async e => {
e.preventDefault();
const resp = await fetch('/api/auth/login', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
email: e.target.email.value,
password: e.target.password.value
})
});
const data = await resp.json();
if (resp.ok) {
localStorage.setItem('token', data.token);
window.location.href = '/dashboard.html';
} else {
alert(data.message);
}
});
</script>