Best Division

Spread Your Knowledge

  • All topics
  • About us
  • Contact us
  • Privacy policy
  • Terms of service
  • Copyright
  • Facebook
  • Twitter
  • Instagram
  • Youtube
  • LinkedIn
  • Pinterest
  • Github
  • Tumblr

© 2026 Best Division

How to Implement Security in Spring Boot Applications

Java
Jayant Kumar
Jayant Kumar@jayantkumar314
PublishedDec 15, 2024
UpdatedNov 16, 2026
6 min read

To secure a Spring Boot application, add spring-boot-starter-security, declare a SecurityFilterChain bean that says which requests need authentication and which roles may call them, and register a PasswordEncoder plus a UserDetailsService. For stateless APIs, validate JWT bearer tokens with the built-in OAuth2 resource server support instead of writing your own filter.

Everything below targets Spring Boot 3.x and later with Spring Security 6 and later. WebSecurityConfigurerAdapter was removed in Spring Security 6, so older tutorials that extend it no longer compile.

Table of Contents

  • What Spring Boot configures when you add Spring Security
  • Declaring a SecurityFilterChain bean
  • Storing users and hashing passwords
  • Securing a stateless API with JWT
  • Method-level authorization
  • CSRF, CORS and security headers
  • Testing your security rules
  • Frequently Asked Questions
    • Should I still extend WebSecurityConfigurerAdapter?
    • Is it safe to disable CSRF?
    • Where should I keep the JWT on the client?
    • What is the difference between a role and an authority?
  • Summary

What Spring Boot configures when you add Spring Security

As soon as spring-boot-starter-security is on the classpath, Boot auto-configures a filter chain that requires authentication for every request, enables form login and HTTP Basic, turns on CSRF protection, and creates a single user account with a random password printed at startup. That default is only a safety net. A real application replaces it with its own configuration.

xml

The core concepts you will configure are:

ConceptWhat it answersMain type
AuthenticationWho is calling?AuthenticationManager, UserDetailsService
AuthorizationWhat may they do?authorizeHttpRequests, method security
Password storageHow are secrets kept?PasswordEncoder
CSRF and CORSWhich browser requests are trusted?csrf(), cors() configuration

Declaring a SecurityFilterChain bean

Since Spring Security 5.7 you configure security by publishing one or more SecurityFilterChain beans and using the lambda DSL. Rules are evaluated top to bottom and the first match wins, so put specific matchers before general ones and finish with anyRequest().

java

hasRole("ADMIN") checks for the authority ROLE_ADMIN, because Spring adds the ROLE_ prefix for you. If you store authorities such as orders:read, use hasAuthority("orders:read") instead.

Storing users and hashing passwords

Never store plain-text or fast-hash (MD5, SHA-1) passwords. Publish a PasswordEncoder and let Spring Security verify credentials through a UserDetailsService. PasswordEncoderFactories.createDelegatingPasswordEncoder() stores the algorithm id with each hash, so you can migrate algorithms later. It uses bcrypt by default.

java

Here UserRepository is your own Spring Data repository. When a user registers, call passwordEncoder.encode(rawPassword) and save only the result.

Securing a stateless API with JWT

For REST APIs consumed by SPAs, mobile apps or other services, use bearer tokens. The simplest production-ready approach is to treat your app as an OAuth2 resource server. An identity provider such as Keycloak, Auth0, Okta or Spring Authorization Server issues the tokens, and your app only validates them.

xml
yaml
java

Boot reads the issuer's metadata, downloads the signing keys, and verifies signature, expiry and issuer on every request. Scopes in the token become authorities prefixed with SCOPE_. Disabling CSRF is acceptable here only because the API does not rely on cookies for authentication.

If you must issue tokens yourself, use a maintained library such as Nimbus JOSE+JWT (already pulled in by the resource server starter) with asymmetric keys, short expiry times and refresh tokens. Do not hard-code secrets or use the unmaintained jjwt 0.9.x line shown in many old tutorials.

Method-level authorization

URL rules are coarse. Use method security to protect service-layer logic where the decision depends on the data.

java

@EnableMethodSecurity replaces the older @EnableGlobalMethodSecurity, and @PreAuthorize and @PostAuthorize are enabled by default with it.

CSRF, CORS and security headers

  • Keep CSRF protection enabled for any app that uses session cookies, such as server-rendered pages. For SPAs on cookies, use the cookie-based token repository CookieCsrfTokenRepository.withHttpOnlyFalse().
  • Configure CORS through a CorsConfigurationSource bean and http.cors(Customizer.withDefaults()). List exact origins, not *, when credentials are allowed.
  • Spring Security sends safe default headers (X-Content-Type-Options, Cache-Control, X-Frame-Options). Add a Content-Security-Policy through http.headers(...) if you serve HTML.
  • Serve everything over HTTPS and enable server.servlet.session.cookie.secure=true and same-site settings for session cookies.

Testing your security rules

Add spring-security-test and verify both the allowed and the denied path.

java

Frequently Asked Questions

Should I still extend WebSecurityConfigurerAdapter?

No. It was deprecated in Spring Security 5.7 and removed in 6.0. Declare a SecurityFilterChain bean instead.

Is it safe to disable CSRF?

Only for stateless APIs that authenticate with an Authorization header and never with cookies. Browsers attach cookies automatically, so cookie-authenticated apps must keep CSRF protection.

Where should I keep the JWT on the client?

Prefer an in-memory variable or an HttpOnly, Secure, SameSite cookie. Avoid localStorage because any XSS bug can read it.

What is the difference between a role and an authority?

A role is an authority with the ROLE_ prefix. hasRole("ADMIN") and hasAuthority("ROLE_ADMIN") are equivalent.

Summary

Add the starter, publish a SecurityFilterChain, hash passwords with a delegating PasswordEncoder, and validate JWTs through the OAuth2 resource server instead of custom filters. Enforce finer rules with @PreAuthorize, keep CSRF on for cookie-based apps, configure CORS explicitly, and cover the rules with spring-security-test.

Share