Video in progress

Junior 🌱 Spring

What is the difference between authentication and authorization?

Authentication is "who are you?": a login, password or token is checked. Authorization is "are you allowed to do this?": a role or permission is checked. The first comes before the second.

📖 Answer

A simple example: you walk into a bank.

  • The guard checks your passport. That's authentication.
  • You want to go into the cashier's back room, but you have no permission. That's authorization.

In HTTP the status codes differ:

Situation Status
No token or a wrong one 401 Unauthorized (it really means "unauthenticated")
Valid token, but the role isn't enough 403 Forbidden

In Spring Security:

  • the result of authentication is an Authentication object held in the SecurityContextHolder;
  • you write authorization with authorizeHttpRequests(...) or @PreAuthorize("hasRole('ADMIN')").
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
auth.getName();          // who
auth.getAuthorities();   // what they have rights to

In interviews people often mix up 401 and 403.