Difference between Authentication and Authorization
Security plays a very important role in every application and website. Two security terms you will meet again and again are authentication and authorization. They sound similar and are often mixed up, but they answer two completely different questions.
This guide explains both concepts in simple terms, compares them side by side, shows how they work together in real systems, and ends with working Java and Spring Security examples.
1. What Is Authentication?
Authentication is the process of verifying who you are. It checks that a user (or another system) really is who they claim to be.
When you log in with a username and password, the application checks those details against what it has stored. If they match, you are authenticated: the system now knows your identity.
Everyday example: when you enter an office building, the security guard checks your ID card to confirm your identity. That identity check is authentication.
Authentication is often shortened to AuthN.
2. Common Authentication Methods
Ways of proving your identity are usually grouped into three kinds, called factors:
| Factor | Meaning | Examples |
|---|---|---|
| Something you know | A secret only you should know | Password, PIN, security question |
| Something you have | A device or object in your possession | Phone with an authenticator app, one-time code by SMS, hardware security key |
| Something you are | A physical characteristic | Fingerprint, face recognition |
Common authentication methods include:
- Username and password: the most common, and the weakest when used alone.
- One-time passwords (OTP): short codes sent by SMS or email, or generated by an authenticator app.
- Biometrics: fingerprint or face recognition, usually to unlock a device or a key stored on it.
- Passkeys: a modern, password-free method where your device proves your identity with a cryptographic key.
- Single sign-on (SSO): one login, for example with your company account, gives access to many applications.
- Certificates and API keys: used when one system, rather than a person, authenticates to another.
Using two or more different factors together is called multi-factor authentication (MFA). Even if an attacker steals your password, they still need your phone or fingerprint.
3. What Is Authorization?
Authorization is the process of deciding what you are allowed to do. It happens after the system knows who you are.
Once you are authenticated, the system checks your permissions to decide which pages, data and actions are open to you, for example:
- Opening admin pages
- Viewing or editing certain records
- Downloading reports
- Deleting or updating data
Everyday example: inside the office building, your card only opens certain rooms. A manager can enter the conference room, but a visitor cannot. That permission check is authorization.
Authorization is often shortened to AuthZ.
4. Common Authorization Models
There are several ways to decide who may do what. Most real systems combine two or more of them.
| Model | How access is decided | Example |
|---|---|---|
| Role-based (RBAC) | Users get roles; roles get permissions | Admins can delete users; customers cannot |
| Attribute-based (ABAC) | Rules use attributes of the user, the data and the situation | Doctors may view records of patients in their own department, during working hours |
| Ownership | Users can act on data they own | You can edit your own profile, but not someone else’s |
| Access control lists (ACL) | Each item keeps a list of who may use it | A shared document lists who can view and who can edit |
| Scopes | A token lists exactly what an application may do | A photo app may read your photos, but not delete them |
Role-based access control is the most common starting point because it is easy to understand and manage. Ownership checks are almost always needed on top of it, so that one customer cannot see another customer’s orders.
5. Key Differences Between Authentication and Authorization
| Authentication | Authorization | |
|---|---|---|
| Question it answers | Who are you? | What are you allowed to do? |
| Order | Happens first | Happens after authentication |
| Based on | Credentials: passwords, codes, fingerprints, keys | Roles, permissions, rules and ownership |
| Focus | Identity | Access control |
| How often | Usually once per login or session | On every request or action |
| Can the user change it? | Partly: users can change their password | No: set by administrators or the system’s rules |
| Visible to the user? | Yes: login screens and codes | Mostly invisible, until access is denied |
| Typical failure | 401 Unauthorized | 403 Forbidden |
| Common technologies | Passwords, MFA, passkeys, OpenID Connect, SAML | RBAC, ABAC, ACLs, OAuth 2 scopes |
| Short name | AuthN | AuthZ |
6. How They Work Together
Authentication and authorization are two steps in the same flow. Here is what happens when a user opens a protected page:
- The user sends a request, for example to view their orders.
- Authentication: the system checks the login session or token. If the user is not logged in, they are asked to log in, and the request stops here.
- The system now knows the user’s identity, such as “alice, role CUSTOMER”.
- Authorization: the system checks whether this user may perform this action on this data. If not, access is denied.
- If both checks pass, the request is processed and the user sees their orders.
Authorization depends on authentication: you cannot decide what someone may do until you know who they are. The one exception is public content, which the system deliberately allows for everyone, including anonymous visitors.
7. Authentication vs Authorization in Real Life
| Situation | Authentication | Authorization |
|---|---|---|
| Online banking | Logging in with your password and a code from your phone | Viewing your accounts and transferring money up to your daily limit |
| Airport | Showing your passport at security | Your boarding pass lets you board only your flight, in your seat class |
| Hospital system | A doctor logs in with a staff card and PIN | The doctor can read records of their own patients, but not edit billing |
| Streaming service | Signing in to your account | Your plan decides whether you can watch in 4K or on several screens |
| Code hosting site | Signing in with a passkey | You can push to your own repositories, but only read others’ |
8. 401 vs 403: What the Errors Mean
Web applications and APIs report failures of the two steps with different HTTP status codes:
| Status code | Which step failed | Meaning | What the user should do |
|---|---|---|---|
401 Unauthorized | Authentication | “We do not know who you are” | Log in, or send valid credentials or a valid token |
403 Forbidden | Authorization | “We know who you are, and you may not do this” | Logging in again will not help; ask for access |
The name “401 Unauthorized” is confusing, because it actually means unauthenticated. It is a historical naming mistake in the HTTP standard that everyone has to live with.
404 Not Found instead of 403 for private data, so that outsiders cannot even tell whether a record exists.9. A Simple Java Example
This plain Java example shows the two steps as two separate classes. It uses the small spring-security-crypto library only for safe password hashing; everything else is plain Java.
The user model:
import java.util.Set;
public enum Role {
CUSTOMER, SUPPORT, ADMIN
}
public enum Action {
VIEW_ORDER, REFUND_ORDER, DELETE_USER
}
public record User(String username, String passwordHash, Set<Role> roles) {
}
public record Order(Long id, String customerUsername) {
}
Step 1, authentication: check the username and password.
import java.util.Map;
import java.util.Optional;
import org.springframework.security.crypto.password.PasswordEncoder;
public class AuthenticationService {
private final Map<String, User> usersByName;
private final PasswordEncoder passwordEncoder;
public AuthenticationService(Map<String, User> usersByName, PasswordEncoder passwordEncoder) {
this.usersByName = usersByName;
this.passwordEncoder = passwordEncoder;
}
/** Answers the question "Who are you?" */
public Optional<User> authenticate(String username, String rawPassword) {
User user = usersByName.get(username);
// Same result for "unknown user" and "wrong password",
// so attackers cannot discover which usernames exist
if (user == null || !passwordEncoder.matches(rawPassword, user.passwordHash())) {
return Optional.empty();
}
return Optional.of(user);
}
}
Step 2, authorization: check what the authenticated user may do.
import java.util.Map;
import java.util.Set;
public class AuthorizationService {
// Which roles may perform which action
private static final Map<Action, Set<Role>> RULES = Map.of(
Action.VIEW_ORDER, Set.of(Role.CUSTOMER, Role.SUPPORT, Role.ADMIN),
Action.REFUND_ORDER, Set.of(Role.SUPPORT, Role.ADMIN),
Action.DELETE_USER, Set.of(Role.ADMIN));
/** Answers the question "What are you allowed to do?" */
public boolean isAllowed(User user, Action action) {
// Anything not listed is denied
Set<Role> allowedRoles = RULES.getOrDefault(action, Set.of());
return user.roles().stream().anyMatch(allowedRoles::contains);
}
/** Ownership check: customers may only view their own orders */
public boolean canViewOrder(User user, Order order) {
if (user.roles().contains(Role.SUPPORT) || user.roles().contains(Role.ADMIN)) {
return true;
}
return order.customerUsername().equals(user.username());
}
}
Putting both steps together:
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
public class SecurityDemo {
public static void main(String[] args) {
PasswordEncoder encoder = new BCryptPasswordEncoder();
User alice = new User("alice", encoder.encode("alice-pass"), Set.of(Role.CUSTOMER));
User sam = new User("sam", encoder.encode("sam-pass"), Set.of(Role.SUPPORT));
AuthenticationService authentication =
new AuthenticationService(Map.of("alice", alice, "sam", sam), encoder);
AuthorizationService authorization = new AuthorizationService();
// Step 1: authentication
Optional<User> result = authentication.authenticate("alice", "alice-pass");
if (result.isEmpty()) {
System.out.println("401: login failed");
return;
}
User user = result.get();
System.out.println("Logged in as " + user.username());
// Step 2: authorization
System.out.println("View order: " + authorization.isAllowed(user, Action.VIEW_ORDER));
System.out.println("Refund order: " + authorization.isAllowed(user, Action.REFUND_ORDER));
System.out.println("Delete user: " + authorization.isAllowed(user, Action.DELETE_USER));
}
}
Logged in as alice
View order: true
Refund order: false
Delete user: false
Alice is authenticated, so the system knows who she is. Authorization then allows her to view orders but denies refunds and deleting users, which would become 403 Forbidden responses in a web application.
10. Authentication and Authorization in Spring Security
In real Java applications you rarely write this code yourself. Spring Security handles both steps. Authentication is configured with a login method, such as form login or tokens; authorization is configured with access rules:
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// AUTHORIZATION: who may open which URLs
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/products/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
// AUTHENTICATION: how users prove who they are
.formLogin(Customizer.withDefaults());
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
For finer control, authorization rules can also be placed on individual methods, including ownership checks:
@Service
public class OrderService {
private final OrderRepository repository;
public OrderService(OrderRepository repository) {
this.repository = repository;
}
// Support staff and admins can refund orders
@PreAuthorize("hasAnyRole('SUPPORT', 'ADMIN')")
public void refund(Long orderId) {
// ...
}
// Customers can only see their own orders; staff can see all
@PostAuthorize("hasAnyRole('SUPPORT', 'ADMIN') "
+ "or returnObject.customerUsername == authentication.name")
public Order findById(Long orderId) {
return repository.findById(orderId).orElseThrow();
}
}
Spring Security returns 401 when a user is not authenticated and 403 when an authenticated user breaks an authorization rule.
11. Tokens, JWT and OAuth 2
Modern applications often use tokens instead of sessions. A token can carry information for both steps:
{
"sub": "alice",
"iss": "https://login.example.com",
"exp": 1791129600,
"roles": ["CUSTOMER"],
"scope": "orders:read profile:read"
}
- Authentication data:
sub(who the user is) andiss(who issued the token). A valid signature proves the token is genuine. - Authorization data:
rolesandscopedescribe what the token holder may do.
Two related standards are often confused:
| Standard | Purpose | Answers |
|---|---|---|
| OAuth 2 | Lets an application act on your behalf with limited permissions, without getting your password | Authorization: “What may this app do?” |
| OpenID Connect | A layer on top of OAuth 2 that adds a standard way to log in | Authentication: “Who is this user?” |
So “Login with Google” is OpenID Connect (authentication), while “Allow this app to read your calendar” is OAuth 2 (authorization). Learn more in What Is JWT.
12. Why Are Both Important?
Authentication and authorization work together to keep systems secure:
- Without authentication, anyone could enter the system and claim to be anyone.
- Without authorization, every logged-in user could read, change or delete everything, including other users’ data.
Weak authorization is one of the most common real-world security problems. “Broken access control” was ranked first in the OWASP Top 10 list of web application risks in 2021: applications that check that a user is logged in, but not whether that user may access the requested data.
13. Common Mistakes to Avoid
| Mistake | Why it is dangerous | Better approach |
|---|---|---|
| Checking login but not permissions | Any logged-in user can open any record by changing an ID in the URL | Check permissions and ownership on every request |
| Hiding buttons instead of enforcing rules | Attackers call the API directly and skip the user interface | Enforce every rule on the server |
| Trusting user IDs sent by the client | A user can send someone else’s ID | Use the identity from the authenticated session or token |
| Different errors for wrong username and wrong password | Attackers learn which usernames exist | Return one generic “invalid credentials” message |
| Storing plain-text passwords | A stolen database exposes every account | Store salted hashes with BCrypt or Argon2 |
| Giving everyone admin rights “for now” | One stolen account can damage everything | Grant the least access needed |
| Long-lived tokens with no expiry | A stolen token works for a long time | Use short expiry times and refresh tokens |
14. Best Practices
- Use proven libraries such as Spring Security instead of writing your own security code.
- Turn on multi-factor authentication, at least for administrators and sensitive actions.
- Hash passwords with BCrypt or Argon2, and never log them.
- Deny by default: anything not explicitly allowed should be refused.
- Follow the principle of least privilege: give each user only the access their job needs.
- Check authorization on the server, on every request, including ownership of the data.
- Use HTTPS everywhere so passwords and tokens cannot be intercepted.
- Log security events such as failed logins and denied access, and review them.
- Test the “no” cases: make sure each role is denied what it should not have.
15. Summary
In simple words, authentication confirms your identity and authorization controls your access. Authentication always comes first and answers “Who are you?” with passwords, codes, passkeys or tokens. Authorization follows on every request and answers “What may you do?” with roles, permissions and ownership rules. A failed authentication returns 401, and a failed authorization returns 403. Both are essential: use strong authentication with MFA, enforce authorization on the server for every request, and rely on proven tools such as Spring Security to implement them correctly.
Frequently Asked Questions (FAQ)
Q1. Can authorization happen without authentication?
Yes, in a limited way. Every system makes authorization decisions for anonymous visitors too: a public product page is “authorized for everyone”, while the checkout page is not.
What is not possible is giving personal permissions, such as “Alice may edit her profile”, without first authenticating Alice. Personal access always needs to know who the user is.
Q2. What is the difference between identification, authentication and authorization?
- Identification: you claim an identity, for example by typing your username.
- Authentication: you prove that claim, for example with your password or fingerprint.
- Authorization: the system decides what that proven identity may do.
Typing “alice” is identification; anyone can type it. Only entering Alice’s correct password authenticates you as Alice.
Q3. What is multi-factor authentication (MFA), and why does it matter?
MFA requires two or more different kinds of proof: something you know, something you have, and something you are. A password plus a code from your phone is a common combination.
It matters because passwords are often stolen through phishing or data breaches. With MFA, a stolen password alone is not enough to log in, which stops the vast majority of account takeover attempts.
Note that two passwords are not MFA; both are “something you know”.
Q4. What are passkeys?
Passkeys are a modern replacement for passwords, based on the WebAuthn and FIDO2 standards. Your device creates a pair of cryptographic keys for each website:
- The private key stays on your device, protected by your fingerprint, face or PIN.
- The public key is stored by the website.
At login, your device proves it holds the private key without ever sending it. There is no password to steal or reuse, and passkeys only work on the real website, so they protect against phishing.
Q5. Is OAuth 2 used for authentication or authorization?
OAuth 2 is an authorization framework. It lets you allow an application to do something on your behalf, such as reading your calendar, without giving it your password.
For logging in, the standard to use is OpenID Connect, which is built on top of OAuth 2 and adds an ID token describing who the user is. “Login with Google” buttons use OpenID Connect.
Q6. What is single sign-on (SSO)?
Single sign-on lets you log in once, with one identity provider, and then use many applications without logging in again. Signing in to your work account and then opening email, chat and documents without further logins is SSO.
SSO handles authentication centrally. Each application still makes its own authorization decisions about what you may do inside it. Common SSO standards are OpenID Connect and SAML.
Q7. What is the difference between a role and a permission?
- A permission is a single allowed action, such as
orders:refundorusers:delete. - A role is a named group of permissions that matches a job, such as Support Agent.
Users are given roles, and roles are given permissions. When a new support agent joins, you assign one role instead of twenty separate permissions.
Q8. Should authorization checks be done in the front end or the back end?
Always in the back end. The front end can and should hide buttons a user cannot use, which improves the experience, but that is not security.
Anyone can call your API directly with tools such as curl or the browser’s developer tools and skip your user interface entirely. Only checks on the server cannot be bypassed.
Q9. What is the principle of least privilege?
Every user, application and service should have only the access it needs to do its job, and nothing more.
- A support agent can view and refund orders but cannot delete user accounts.
- A reporting service can read the database but cannot write to it.
If an account is stolen or misused, least privilege limits the damage to what that account could do.
Q10. Why do login forms say "invalid username or password" instead of which one is wrong?
To prevent username enumeration. If the message said “unknown username”, an attacker could try thousands of names and learn which accounts exist, then focus their password guessing on those.
A single generic message gives nothing away. For the same reason, “forgot password” pages should say “if this email is registered, we have sent a link” whether or not the account exists.
Q11. What is broken access control?
It is the name for authorization mistakes that let users do things they should not, for example:
- Changing
/orders/1001to/orders/1002in the URL and seeing another customer’s order. - A normal user calling an admin API that only hides its button in the interface.
- Changing a
rolefield in a request to become an admin.
The fix is to check, on the server and for every request, both the user’s permissions and whether they own the data.
Q12. What is step-up authentication?
Step-up authentication asks an already logged-in user to prove their identity again, often with a stronger factor, before a sensitive action. Examples:
- Entering your password again before changing your email address.
- Confirming a large bank transfer with a code from your phone.
It protects users if someone else gets hold of their unlocked device or a stolen session.
Q13. What happens if a user's role changes while they are logged in?
It depends on where the role information is stored:
- Sessions: roles are usually loaded at login, so the change may only apply after the user logs in again, unless the application reloads them or ends the session.
- Tokens such as JWT: the old roles stay in the token until it expires.
To make changes take effect quickly, use short token lifetimes, end the user’s sessions when their access is reduced, or check important permissions against the database.
Q14. How do API keys fit into authentication and authorization?
An API key mainly authenticates an application, not a person: it tells the server which client is calling. The server then authorizes that client, for example allowing read-only access or a limited number of requests per minute.
API keys are simple but have no built-in expiry and are easy to leak in code or logs. Store them as secrets, rotate them regularly, and give each key only the permissions it needs. For acting on behalf of users, OAuth 2 tokens are a better fit.
Q15. What is zero trust?
Zero trust is a security approach summed up as “never trust, always verify”. Being inside the company network does not grant access by itself.
- Every request is authenticated, even between internal services.
- Every request is authorized with least privilege.
- Device health and context, such as location, can be part of the decision.
It limits how far an attacker can move after getting into one part of the system.
Q16. How should an application handle repeated failed login attempts?
Combine several measures so attackers cannot guess passwords quickly:
- Rate limiting: slow down or block many attempts from the same address.
- Temporary lockout or increasing delays after several failures on one account.
- CAPTCHA after suspicious activity.
- MFA, so a guessed password is not enough.
- Monitoring and alerts for unusual spikes in failures.
Avoid permanent lockouts: attackers could use them to lock real users out deliberately.
Q17. What is the difference between session-based and token-based authentication?
| Session-based | Token-based | |
|---|---|---|
| After login | Server stores a session, browser keeps a cookie | Client receives a signed token, such as a JWT |
| On each request | Cookie sent automatically | Token sent in the Authorization header |
| Logout | Immediate: delete the session | Token stays valid until it expires |
| Typical use | Traditional websites | Mobile apps, APIs, microservices |
Both are ways of remembering an authentication. Authorization rules are applied the same way afterwards.
Q18. Do I need to log authentication and authorization events?
Yes. Security logs help you spot attacks and investigate incidents. Useful events include:
- Successful and failed logins, with time and source address.
- Password changes, MFA changes and account lockouts.
- Denied access attempts (
403), especially repeated ones. - Changes to roles and permissions.
Never log passwords, full tokens or other secrets. This tracking is sometimes called the third “A” in AAA: authentication, authorization and accounting.
Q19. How can I test that authorization rules really work?
Write automated tests for the denied cases as well as the allowed ones:
- For each role, test at least one action it must not be able to perform.
- Test that user A cannot read or change user B’s data by changing IDs.
- Test that requests without login get
401and forbidden requests get403.
With Spring Security, @WithMockUser(roles = "CUSTOMER") makes these tests short. Run them on every build so a refactoring cannot silently open access.
Q20. Which comes first in a request: authentication or authorization?
Authentication always comes first. The system must know who is making the request before it can decide what they may do.
In frameworks such as Spring Security, an authentication filter runs early in the request and sets the current user; an authorization filter or method check runs afterwards and uses that user. If authentication fails, the request never reaches the authorization step and the response is 401.