Spring Security Authentication, Authorization, JWT, and OAuth2
What is Spring Security?
Section titled “What is Spring Security?”Spring Security is a powerful authentication and authorization framework used to secure Java applications, especially Spring Boot applications.
It provides protection for:
- REST APIs
- Web applications
- Microservices
- Method-level security
Main Features
Section titled “Main Features”- Authentication (Who are you?)
- Authorization (What can you access?)
- Protection against attacks:
- CSRF
- Session fixation
- Clickjacking
- Password encryption
- Integration with JWT, OAuth2, and LDAP
Example
Section titled “Example”@Configuration@EnableWebSecuritypublic class SecurityConfig {
@Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http .authorizeHttpRequests(auth -> auth .requestMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() ) .formLogin();
return http.build(); }}Spring Security Filter Chain
Section titled “Spring Security Filter Chain”flowchart LR
A[HTTP Request] --> B[Spring Security Filter Chain]
B --> C[Authentication]
C --> D[Authorization]
D --> E[Controller]
Authentication vs Authorization
Section titled “Authentication vs Authorization”| Feature | Authentication | Authorization |
|---|---|---|
| Definition | Verifies who the user is | Determines what the user can access |
| Question | Who are you? | What are you allowed to do? |
| Happens | First | After authentication |
| Example | Login with username/password | Access admin APIs |
| Data Used | Credentials | Roles/Permissions |
Example Flow
Section titled “Example Flow”- User logs in.
Username: adminPassword: password-
System verifies the user and generates a token.
-
User requests:
GET /admin/users- Authorization checks:
ROLE_ADMIN -> AllowedROLE_USER -> DeniedInterview one-liner: Authentication verifies identity, while Authorization determines access permissions.
JWT Authentication
Section titled “JWT Authentication”JWT (JSON Web Token) is a stateless authentication mechanism commonly used for REST APIs and microservices.
Instead of server-side sessions, the server issues a signed token.
JWT Structure
Section titled “JWT Structure”Header.Payload.SignatureExample:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMSIsInJvbGUiOiJBRE1JTiJ9.signatureAuthentication Flow
Section titled “Authentication Flow”sequenceDiagram
participant C as Client
participant S as Server
C->>S: POST /login (username/password)
S->>S: Validate credentials
S-->>C: JWT Token
C->>S: Authorization: Bearer <token>
S->>S: Validate JWT
S-->>C: Protected Resource
Login Request
Section titled “Login Request”POST /login{ "username":"user", "password":"123"}Authorization Header
Section titled “Authorization Header”Authorization: Bearer <token>Spring Boot JWT Flow
Section titled “Spring Boot JWT Flow”flowchart TD
A[Request] --> B[JWT Filter]
B --> C[Validate Token]
C --> D[Set Authentication in SecurityContext]
D --> E[Controller]
Benefits
Section titled “Benefits”- Stateless authentication
- Scalable for microservices
- No server-side session storage
- Ideal for REST APIs
Securing APIs with OAuth2
Section titled “Securing APIs with OAuth2”OAuth2 is an authorization framework that enables secure API access using access tokens instead of sharing user credentials.
OAuth2 Flow
Section titled “OAuth2 Flow”sequenceDiagram
participant U as User
participant C as Client App
participant A as Authorization Server
participant R as Resource Server
U->>C: Login
C->>A: Authorization Request
A->>U: Authenticate
U-->>A: Credentials
A-->>C: Access Token
C->>R: Bearer Token
R-->>C: Protected Resource
Components
Section titled “Components”| Component | Description |
|---|---|
| Resource Owner | User |
| Client | Application |
| Authorization Server | Issues tokens |
| Resource Server | Protected API |
Spring Boot Dependency
Section titled “Spring Boot Dependency”spring-boot-starter-oauth2-resource-serverExample Configuration
Section titled “Example Configuration”@Configuration@EnableWebSecuritypublic class SecurityConfig {
@Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) .oauth2ResourceServer(oauth -> oauth.jwt());
return http.build(); }}Example
Section titled “Example”- User logs in with Google.
- Google authenticates the user.
- Google returns an access token.
- Client calls the API using:
Authorization: Bearer abc123- Resource server validates the token.
Key Takeaways
Section titled “Key Takeaways”- Spring Security provides authentication, authorization, and protection against common web attacks.
- Authentication verifies identity; authorization determines permissions.
- JWT enables stateless authentication by sending a signed token with each request.
- OAuth2 provides secure delegated authorization using access tokens.
- Spring Boot integrates JWT and OAuth2 through Spring Security’s filter chain and resource server support.