Spring Security


๐Ÿง  What Is Spring Security?

๐Ÿ‘‰ Spring Security is a powerful authentication and authorization framework that comes as part of the Spring ecosystem.
It helps protect your Java and Spring Boot applications from unauthorized access, by managing:

  • Who can access your app (Authentication โœ…)
  • What they can do once logged in (Authorization ๐Ÿ”’)

โš™๏ธ Why We Need Spring Security

Without security:

  • Anyone can call your APIs
  • No protection against attackers
  • No control over user access

With Spring Security, you get:

  • Login/logout mechanisms
  • Role-based access control
  • Token-based authentication (JWT, OAuth2)
  • Protection from common attacks (CSRF, XSS, Clickjacking)

๐Ÿ”‘ Two Core Concepts

1๏ธโƒฃ Authentication

โ€œWho are you?โ€

It verifies the identity of a user.
Example: username + password login, JWT token, OAuth2.

Authentication auth = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(username, password)
);

2๏ธโƒฃ Authorization

โ€œWhat can you do?โ€

It checks whether an authenticated user has permission to perform an action.

Example:

@PreAuthorize("hasRole('ADMIN')")
public String getAllUsers() { ... }

๐Ÿงฉ How Spring Security Works (Flow)

  1. You make a request (e.g. GET /api/data)
  2. The Security Filter Chain intercepts it
  3. If youโ€™re not authenticated โ†’ it blocks or redirects you
  4. If authenticated โ†’ it checks your roles/permissions
  5. If authorized โ†’ the controller executes

๐Ÿ”’ Example

Default Behavior

If you add spring-boot-starter-security to your project and run it:

  • Every endpoint becomes secured by default
  • Spring creates a default user with a generated password in logs
  • You can log in at /login

Thatโ€™s how Spring Security ensures “secure by default”.


๐Ÿงฑ Common Use Cases

ScenarioSpring Security Feature
Login formUsernamePasswordAuthenticationFilter
JWT Token AuthenticationCustom Filter + Stateless Security
OAuth2 Login (Google, GitHub)spring-boot-starter-oauth2-client
Method-level security@PreAuthorize, @Secured
Protect REST APIsStateless Authentication with JWT

๐Ÿ” Example Configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig {

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

โœ… /public/** โ†’ accessible to all
๐Ÿ”’ all others โ†’ require authentication


๐Ÿง  In Short

ConceptMeaning
AuthenticationVerifying identity
AuthorizationGranting access based on roles
Filter ChainIntercepts every request
Security ContextStores authenticated user details
Stateless AuthCommon for REST APIs using JWT

๐Ÿš€ Why Developers Use It

  • Works seamlessly with Spring Boot
  • Highly customizable
  • Integrates with databases, LDAP, JWT, OAuth2
  • Enterprise-grade security with minimal setup

Read other awesome articles inย Medium.com or in akcoding’s posts.

OR

Join us on YouTube Channel

OR Scan the QR Code to Directly open the Channel ๐Ÿ‘‰

AK Coding YouTube Channel

Share with