Sections in this lesson
Spring Security Fundamentals
Separate authentication, resource authorization and CSRF protection before exposing an AI endpoint.
Reviewed: · Content owner: Interview Preparator
What you will learn
- Distinguish authentication, roles and ownership.
- Keep CSRF protection aligned with the client credential model.
- Test both denied and allowed resource paths.
Before you start
The flow
- 1.Authenticate
- 2.Authorize route
- 3.Check CSRF
- 4.Resolve ownership
- 5.Execute
Authentication is only the beginning
Authentication identifies the caller; authorization decides which resource and action they may access. A shared STUDENT role does not permit reading another tenant's documents. Enforce resource policy inside retrieval and tool services as well as at the HTTP route.
The lab uses two in-memory Basic Auth users only for a local teaching flow, with BCrypt hashes created from required environment passwords. Production identity, account lifecycle and credential delivery are separate concerns.
Match CSRF policy to credentials
Browsers can automatically attach credentials, including Basic Auth credentials. Do not disable CSRF just because a route returns JSON. This lab keeps Spring Security CSRF protection and obtains a token from an authenticated endpoint before POST.
For OAuth2, distinguish interactive login from a resource server validating bearer access tokens. Check issuer, audience, expiry and scopes. A bearer-only API may have a different CSRF design, but that is an explicit credential and threat-model decision.
Denied paths need evidence
Tests should prove that no evidence or tool action is available on denied paths. A correct final answer cannot excuse a forbidden intermediate read. The local application binds to loopback; extending it beyond a workstation requires TLS, real identity management, limits and operational review.
Try it
package com.interviewpreparator.lab;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.factory.PasswordEncoderFactories;import org.springframework.security.provisioning.InMemoryUserDetailsManager;import org.springframework.security.web.SecurityFilterChain;@Configurationpublic class SecurityConfiguration { @Bean UserDetailsService users(@Value("${lab.alpha-password}") String alpha, @Value("${lab.beta-password}") String beta) { if (alpha.length() < 12 || beta.length() < 12) throw new IllegalArgumentException("Use at least 12 characters per demo password"); var encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); return new InMemoryUserDetailsManager( User.withUsername("alpha").password(encoder.encode(alpha)).roles("STUDENT").build(), User.withUsername("beta").password(encoder.encode(beta)).roles("STUDENT").build()); } @Bean SecurityFilterChain security(HttpSecurity http) throws Exception { return http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .httpBasic(Customizer.withDefaults()).csrf(Customizer.withDefaults()).build(); }}examples/spring-ai-lab/src/main/java/com/interviewpreparator/lab/SecurityConfiguration.java · mvn -f examples/spring-ai-lab/pom.xml -Pintegration verify. Java 21+, Spring Boot 4.0.5, Spring AI 2.0.2 where applicable. The demo uses synthetic models; live inference quality is a separate check.
Interview questions
Does a role prove document ownership?
No. Check tenant and resource ownership using trusted identity at the access boundary.
Why keep CSRF for Basic Auth?
A browser can attach credentials automatically; an attacker may otherwise induce an authenticated write.
What is OAuth2 resource-server validation?
Validation of an access token and its permitted audience/scopes before mapping the caller to resource policies.
Practice
Add a third principal with no tenant mapping and verify that no retrieval can occur.
Check your solution
- Authentication alone never grants foreign-tenant access.
- POST without a CSRF token is denied in the Basic Auth flow.
- No password is placed in a committed file or frontend bundle.
Official references
Continue learning
Category sequence
Spring & Spring Boot
Lesson 4 / 4
Was this lesson useful?
Change notes: Phase 2: bilingual lesson with versioned executable reference.