Spring security basics

 Here’s a structured overview of Spring Security—Spring’s powerful framework for securing Java applications, especially RESTful services and web apps:


1. What Is Spring Security?

  • A comprehensive, customizable framework for authentication (who you are) and authorization (what you’re allowed to do).

  • Integrates as a filter chain around your web endpoints or method invocations.

  • Ships with defaults that protect against common attacks (CSRF, session fixation, clickjacking).


2. Core Concepts

2.1 Authentication

  • SecurityFilterChain intercepts requests and delegates to an AuthenticationManager.

  • AuthenticationProvider implementations (e.g., DaoAuthenticationProvider) consult a UserDetailsService to load user data.

  • Credentials (username/password) are checked using a PasswordEncoder (BCrypt, PBKDF2, etc.).

2.2 Authorization

  • After authentication, a user’s GrantedAuthority list (roles/permissions) is stored in an Authentication token.

  • URL-based rules via HttpSecurity (e.g. .antMatchers("/admin/**").hasRole("ADMIN")).

  • Method-level security with annotations:

    • @PreAuthorize("hasRole('USER')")

    • @PostAuthorize, @Secured("ROLE_ADMIN")


3. Configuration Styles

3.1 Legacy (WebSecurityConfigurerAdapter)

@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated() .and() .formLogin(); } }

3.2 Modern (Spring Boot 2.7+)

@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth .requestMatchers("/public/**").permitAll() .anyRequest().authenticated() ) .httpBasic(); return http.build(); }

4. Common Features

  • CSRF Protection: Enabled by default for browser clients.

  • CORS: Configurable per endpoint to allow cross-origin requests.

  • Session Management: Prevent session fixation, control concurrency.

  • Remember-Me: Persistent login via tokens or cookies.


5. Advanced Topics

  • Password Encoding: Always store hashes (e.g., new BCryptPasswordEncoder()).

  • JWT / OAuth2:

    • Resource Server: Validates JWTs on incoming requests.

    • Authorization Server: Issues tokens (via Spring Authorization Server).

  • Method Security: Enable via @EnableGlobalMethodSecurity(prePostEnabled = true).

  • Security Testing:

    • @WithMockUser for mock authentication in tests.

    • SecurityMockMvcRequestPostProcessors for MockMvc.


6. Why Use Spring Security?

  • Convention + Configuration: Sensible defaults with easy overrides.

  • Extensible: Plug in custom filters, providers, and voters.

  • Ecosystem Integration: Works seamlessly with Spring Boot, Spring Cloud, and OAuth2/JWT standards.


Next Steps:

  1. Hands-On: Secure a sample Spring Boot app with form login, then migrate to JWT.

  2. Explore: Add OAuth2 resource-server support and method-level security.

  3. Practice: Write unit and integration tests covering secured endpoints.

This foundation will arm you to both configure and extend Spring Security in real-world applications.

Common Attacks

Here’s a deeper look at the three “common attacks” that Spring Security defends against by default:


1. Cross-Site Request Forgery (CSRF)

What it is:
An attacker tricks a logged-in user’s browser into sending unintended requests (e.g. form submits, state-changing GETs) to your app, using the user’s session and credentials.

How it works:

  1. Victim logs into your bank application at bank.com and gets a valid session cookie.

  2. Attacker lures victim to a malicious site that issues a hidden POST to bank.com/transfer?amount=1000&to=attacker.

  3. Browser includes the bank session cookie automatically—so the transfer goes through under the victim’s identity.

Spring Security’s protection:

  • It issues a unique CSRF token per session and expects it in every state-changing request (POST, PUT, DELETE).

  • If the token is missing or wrong, the request is rejected (HTTP 403).

Configuring CSRF:

http // enabled by default; to disable (e.g. for APIs), do: .csrf(csrf -> csrf.disable());

2. Session Fixation

What it is:
An attacker forces a known session ID on a victim (e.g. by sending a link with ?jsessionid=ABC123). If the app doesn’t change that ID after login, the attacker can hijack the authenticated session.

How it works:

  1. Attacker visits your site and gets session ID S1.

  2. Attacker sends victim a URL embedding S1.

  3. Victim logs in using S1.

  4. Attacker reuses S1 and is “logged in” as the victim.

Spring Security’s protection:

  • On successful authentication, it automatically migrates (changes) the session ID, invalidating the old one.

Configuring session fixation policy:

http .sessionManagement(sm -> sm // options: none, migrateSession (default), newSession, changeSessionId .sessionFixation(SessionFixationConfigurer::migrateSession) );

3. Clickjacking

What it is:
An attacker embeds your site in a (transparent) <iframe> on their malicious page, then overlays UI elements to trick users into clicking “hidden” buttons on your site.

How it works:

  1. Attacker creates a page with <iframe src="https://your-app.com/approve" style="opacity:0">.

  2. User thinks they’re clicking a harmless button on the attacker’s page, but they’re actually clicking “Approve” in your app.

Spring Security’s protection:

  • Sends the HTTP header X-Frame-Options: DENY (or SAMEORIGIN), which tells browsers to prevent framing.

Configuring frame options:

http .headers(headers -> headers // DENY prevents all framing; SAMEORIGIN allows only your own domain .frameOptions(FrameOptionsConfig::deny) );

Beyond These Three

While CSRF, session fixation, and clickjacking are enabled out-of-the-box, you should also consider:

  • XSS (Cross-Site Scripting): Sanitize user input or use templating that auto-escapes.

  • SQL Injection: Always use parameterized queries or JPA repositories.

  • Brute-Force Protection: Limit login attempts or add CAPTCHA.

  • SSL/TLS Enforcement: Redirect HTTP to HTTPS, use HSTS.

Together, these defenses form a solid baseline—Spring Security’s defaults cover the top web threats so you can focus on your business logic.

Comments

Popular Posts