Authentication and authorization
What you will learn
Authentication identifies an actor; authorization checks what that actor may do to a particular object. A role alone does not establish tenant ownership.
- Distinguish principal, credentials and authorities.
- Apply server-owned tenant membership checks.
- Explain method security and adaptive password encoding.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Spring Security examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
Membership beyond scope
public class Main { static final java.util.Map<String,String> MEMBERS=java.util.Map.of("alice","north","bob","south"); static boolean allowed(String actor,String tenant,boolean scope){return actor!=null&&tenant!=null&&scope&&tenant.equals(MEMBERS.get(actor));} public static void main(String[] args) {System.out.println(allowed("alice","north",true));System.out.println(allowed("alice","south",true));System.out.println(allowed("bob","south",false)); }}Expected output:
truefalsefalseThe actor is assumed already verified. A valid scope does not authorize access to other tenants.
Identity and object authorization
AuthenticationManager delegates credential checks to configured providers. A successful Authentication supplies a principal and granted authorities; the principal name is not an arbitrary request field. Roles are conventionally ROLE_ prefixed; hasRole("READER") checks ROLE_READER, while hasAuthority compares the exact authority. JWT scopes commonly map to SCOPE_ authorities. A request may carry tenant north but this is only a selector, not proof of membership. Resolve membership from server-owned records keyed by an identity bound to the trusted issuer; this lab accepts one issuer and maps fictional subjects. Unknown subjects and tenants are denied. Real multi-issuer systems need issuer plus subject and an appropriate membership store. For writes, check access and perform mutation within a suitable transaction; avoid a check-then-act race. Use scoped queries or equivalent object checks rather than filtering unauthorized results after fetching.
Method security and passwords
@EnableMethodSecurity activates method authorization; @PreAuthorize evaluates an expression before the proxied method runs. Call the public service through its Spring proxy: a self-call can bypass advice. The lab requires both scope and membership at the service even if another entry point calls it. PasswordEncoder encodes passwords with an adaptive one-way function and verifies with matches(raw,encoded). DelegatingPasswordEncoder supports an algorithm identifier for migration; the factory currently chooses bcrypt for new encodings. Use a reviewed adaptive algorithm and tune cost on the deployed system; never store cleartext, use plain SHA-256 as a password store or log raw input. The in-memory user is lab-only, with a synthetic test password; production account stores and password policy require separate review. Return generic login errors, avoid leaking object existence, and log only appropriately redacted security events.
Exact authority matching
public class Main {
public static void main(String[] args) {var authorities=java.util.Set.of("ROLE_READER","SCOPE_report.read");System.out.println(authorities.contains("ROLE_READER"));System.out.println(authorities.contains("READER"));System.out.println(authorities.contains("SCOPE_report.write")); }}Expected output:
truefalsefalseRoles, read scopes and write scopes have different meanings; do not accept an authority from request input.
Server-owned membership policy
Source-reviewed, NOT RUN. File lab-fixtures/spring-security-v41/src/main/java/example/tenant/TenantAccess.java; use the companion lab README.
package example.tenant;import java.util.Map;import org.springframework.security.core.Authentication;import org.springframework.stereotype.Component;@Component("tenantAccess")public class TenantAccess { private final Map<String,String> membership = Map.of("alice","north","bob","south"); public boolean allowed(Authentication actor, String tenant) { return actor != null && actor.isAuthenticated() && tenant != null && tenant.equals(membership.get(actor.getName())); }}Predicted behavior: Alice has north membership only; Bob has south membership only.
Synthetic membership comes from a server-owned map, never from the requested tenant.
Method authorization
Source-reviewed, NOT RUN. File lab-fixtures/spring-security-v41/src/main/java/example/tenant/ReportService.java; use the companion lab README.
package example.tenant;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.security.core.parameters.P;import org.springframework.stereotype.Service;@Servicepublic class ReportService { @PreAuthorize("hasAuthority('SCOPE_report.read') and @tenantAccess.allowed(authentication, #tenant)") public String report(@P("tenant") String tenant) { return "report for " + tenant; // Synthetic response; no database. }}Predicted behavior: A proxied call without scope or membership is denied.
@P names the method parameter explicitly for the authorization expression.
Common mistakes
Never trust a user ID or role supplied in a request body, use role checks as a substitute for object access, store a password using reversible encryption, or expose a self-invoked method as a supposed proxy boundary.
Practice
Implement a server-owned membership check for alice/north and bob/south; print the results for unknown subject, wrong tenant, missing scope and authorized bob/south.
Expected output:
falsefalsefalsetrueCompare with the manual review criteria.
Official reading: Authorization · Method · Password. Spring execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Authentication and authorization — knowledge check
Spring Security identity and authorization reasoning.
What does authentication establish?
What does hasRole("READER") normally require?
A user has report.read but belongs to north. Can they read south automatically?
Why call a secured service through its proxy?
How should a stored password be verified?