Authentication vs Authorization
Authentication vs Authorization
Explain the difference between Authentication and Authorization. How would you implement them in a web application context?
- Authentication is like the question "Who are you?". It validates the identity of a user, client, or server.
- Authorization is like "What are you allowed to do?". It validates that the authenticated user has permission to access a specific resource or perform a specific action.
Implementing Authentication
For authentication, I generally avoid rolling my own crypto and prefer industry-standard protocols.
I would likely use JWTs (JSON Web Tokens) or session-based cookies, depending on whether the app is stateless (like a REST API) or stateful.
The Authentication Flow:
- The user sends credentials (username/password) to the server.
- I verify these against the hashed passwords in the database - using a strong algorithm like
Argon2orbcrypt. - If valid, I issue a token (like a JWT) containing the user's ID and maybe a role claim, signed with a private secret.
- I'd implement MFA (Multi-Factor Authentication) for sensitive accounts and ensure all transmission happens over HTTPS to prevent interception.
Implementing Authorization
For authorization, I need to decide on an access control model. My go-to is usually RBAC (Role-Based Access Control) because it scales well, though I might use ABAC (Attribute-Based Access Control) for more complex, granular needs.
The Authorization Flow:
I would implement middleware in the backend:
- When a request hits an endpoint (e.g.,
DELETE /api/users/5), the middleware first validates the Authentication token. - It then extracts the user's
rolefrom the token or database. - Finally, it checks a policy: Does the role 'Editor' have permission to 'DELETE' users?
- If yes, the controller executes. If no, I return a
403 Forbiddenstatus.
Summary
| Feature | Authentication (AuthN) | Authorization (AuthZ) |
|---|---|---|
| Question | Who are you? | What are you allowed to do? |
| Key Artifact | Credentials (Password, Biometrics, OTP) | Policies, Roles, Scopes |
| Standard | OpenID Connect, SAML | OAuth 2.0 |
| Error Code | 401 Unauthorized | 403 Forbidden |