00:00

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:

FactorMeaningExamples
Something you knowA secret only you should knowPassword, PIN, security question
Something you haveA device or object in your possessionPhone with an authenticator app, one-time code by SMS, hardware security key
Something you areA physical characteristicFingerprint, 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.

ModelHow access is decidedExample
Role-based (RBAC)Users get roles; roles get permissionsAdmins can delete users; customers cannot
Attribute-based (ABAC)Rules use attributes of the user, the data and the situationDoctors may view records of patients in their own department, during working hours
OwnershipUsers can act on data they ownYou can edit your own profile, but not someone else’s
Access control lists (ACL)Each item keeps a list of who may use itA shared document lists who can view and who can edit
ScopesA token lists exactly what an application may doA 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

AuthenticationAuthorization
Question it answersWho are you?What are you allowed to do?
OrderHappens firstHappens after authentication
Based onCredentials: passwords, codes, fingerprints, keysRoles, permissions, rules and ownership
FocusIdentityAccess control
How oftenUsually once per login or sessionOn every request or action
Can the user change it?Partly: users can change their passwordNo: set by administrators or the system’s rules
Visible to the user?Yes: login screens and codesMostly invisible, until access is denied
Typical failure401 Unauthorized403 Forbidden
Common technologiesPasswords, MFA, passkeys, OpenID Connect, SAMLRBAC, ABAC, ACLs, OAuth 2 scopes
Short nameAuthNAuthZ

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:

  1. The user sends a request, for example to view their orders.
  2. 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.
  3. The system now knows the user’s identity, such as “alice, role CUSTOMER”.
  4. Authorization: the system checks whether this user may perform this action on this data. If not, access is denied.
  5. 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

SituationAuthenticationAuthorization
Online bankingLogging in with your password and a code from your phoneViewing your accounts and transferring money up to your daily limit
AirportShowing your passport at securityYour boarding pass lets you board only your flight, in your seat class
Hospital systemA doctor logs in with a staff card and PINThe doctor can read records of their own patients, but not edit billing
Streaming serviceSigning in to your accountYour plan decides whether you can watch in 4K or on several screens
Code hosting siteSigning in with a passkeyYou 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 codeWhich step failedMeaningWhat the user should do
401 UnauthorizedAuthentication“We do not know who you are”Log in, or send valid credentials or a valid token
403 ForbiddenAuthorization“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.

Tip: Some applications deliberately return 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:

Role.java, Action.java, User.java, Order.java
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.

AuthenticationService.java
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.

AuthorizationService.java
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:

SecurityDemo.java
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));
    }
}
Output
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:

SecurityConfig.java
@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:

OrderService.java
@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:

Decoded JWT payload
{
  "sub": "alice",
  "iss": "https://login.example.com",
  "exp": 1791129600,
  "roles": ["CUSTOMER"],
  "scope": "orders:read profile:read"
}
  • Authentication data: sub (who the user is) and iss (who issued the token). A valid signature proves the token is genuine.
  • Authorization data: roles and scope describe what the token holder may do.

Two related standards are often confused:

StandardPurposeAnswers
OAuth 2Lets an application act on your behalf with limited permissions, without getting your passwordAuthorization: “What may this app do?”
OpenID ConnectA layer on top of OAuth 2 that adds a standard way to log inAuthentication: “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

MistakeWhy it is dangerousBetter approach
Checking login but not permissionsAny logged-in user can open any record by changing an ID in the URLCheck permissions and ownership on every request
Hiding buttons instead of enforcing rulesAttackers call the API directly and skip the user interfaceEnforce every rule on the server
Trusting user IDs sent by the clientA user can send someone else’s IDUse the identity from the authenticated session or token
Different errors for wrong username and wrong passwordAttackers learn which usernames existReturn one generic “invalid credentials” message
Storing plain-text passwordsA stolen database exposes every accountStore salted hashes with BCrypt or Argon2
Giving everyone admin rights “for now”One stolen account can damage everythingGrant the least access needed
Long-lived tokens with no expiryA stolen token works for a long timeUse 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.