DEV Community

sonali kumari shahi
sonali kumari shahi

Posted on

10 Spring Security Configurations Every Beginner Should Know

While learning Spring Security, I found myself searching for the same configurations again and again.

Questions like:

  • How do I make an endpoint public?

  • How do I restrict an API to admin users?

  • How do I disable CSRF for REST APIs?

  • How do I add a JWT filter?

So, I decided to create a small cheatsheet containing some of the Spring Security configurations I use most often while building projects.

If you're getting started with Spring Security, I hope this saves you some time.

1. Allow Public Endpoints

Use permitAll() when an endpoint should be accessible without authentication.

.requestMatchers("/login", "/signup").permitAll()
Enter fullscreen mode Exit fullscreen mode

2. Require Authentication

Use authenticated() when users must log in before accessing an endpoint.

.anyRequest().authenticated()
Enter fullscreen mode Exit fullscreen mode

3. Restrict Access Based on Roles

Allow only ADMIN users to access specific APIs.

.requestMatchers("/admin/**").hasRole("ADMIN")
Enter fullscreen mode Exit fullscreen mode

4. Allow Multiple Roles

When more than one role should have access:

.requestMatchers("/dashboard/**")
.hasAnyRole("USER", "ADMIN")
Enter fullscreen mode Exit fullscreen mode

5. Disable CSRF for REST APIs

In stateless REST APIs, CSRF protection is often disabled.

http.csrf(csrf -> csrf.disable());
Enter fullscreen mode Exit fullscreen mode

6. Define a Password Encoder

Never store passwords in plain text.

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
Enter fullscreen mode Exit fullscreen mode

7. Enable HTTP Basic Authentication

Useful while learning or testing APIs.

http.httpBasic(Customizer.withDefaults());
Enter fullscreen mode Exit fullscreen mode

8. Use Stateless Sessions (JWT)

When building JWT-based applications:

http.sessionManagement(session ->
    session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
Enter fullscreen mode Exit fullscreen mode

9. Add a Custom JWT Filter

Register your JWT filter before Spring's authentication filter.

http.addFilterBefore(
    jwtAuthFilter,
    UsernamePasswordAuthenticationFilter.class
);
Enter fullscreen mode Exit fullscreen mode

10. Get the Currently Logged-in User

Access details of the authenticated user.

Authentication authentication =
    SecurityContextHolder.getContext().getAuthentication();

String username = authentication.getName();
Enter fullscreen mode Exit fullscreen mode

Putting It All Together

A beginner-friendly security configuration might look like this:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http)
        throws Exception {

    http
        .csrf(csrf -> csrf.disable())

        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/login", "/signup")
            .permitAll()

            .requestMatchers("/admin/**")
            .hasRole("ADMIN")

            .anyRequest()
            .authenticated()
        )

        .httpBasic(Customizer.withDefaults());

    return http.build();
}

Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Spring Security can feel overwhelming at first because there are so many configurations to remember.

The good news?

You don't need to memorize everything.

Over time, you'll notice that you keep using the same patterns again and again.

I created this cheatsheet mainly for myself, but I hope it helps other developers who are starting their Spring Security journey as well.

Which Spring Security configuration do you use most often? Let me know in the comments! ๐Ÿ˜Š

Top comments (2)

Collapse
 
merbayerp profile image
Mustafa ERBAY

Good list.

One lesson I learned the hard way is that Spring Security becomes much easier once you stop memorizing configurations and start understanding the request flow.

Authentication, authorization, filters, sessions, and security context all make a lot more sense when you see how a request moves through the chain.

Collapse
 
sonalishahi profile image
sonali kumari shahi

Totally agree ๐Ÿ‘ Once the flow is clear, the configurations start to make a lot more sense.