Guide Spring Boot Authentication

Security in Spring Boot with JWT and Spring Security

March 29, 2026 8 min read

Security in Spring Boot involves more than adding a login endpoint. A reliable API needs clear authentication, authorization, password storage, token handling, endpoint rules, and safe defaults.

Quick Answer

To add security to Spring Boot, start with Spring Security, configure a SecurityFilterChain, encode passwords with BCrypt, and define how JWTs authenticate requests. Keep the application stateless and make authorization rules explicit for each role.

Authentication is one of the first things every backend project needs, but secure authentication is only one part of the system. Production APIs also need authorization, protected credentials, predictable errors, and tests that prove access rules work.

The real challenge is configuring these concerns as one coherent security boundary instead of scattering checks across controllers.

What Security in Spring Boot Includes

  • Authentication that verifies a user's identity
  • Authorization that controls which resources each role can use
  • BCrypt password encoding and safe credential handling
  • Endpoint rules, CORS and CSRF policy, session behavior, security tests, logging, and consistent failure responses

Authentication Versus Authorization

  • Authentication confirms who is making the request, usually by validating credentials or a JWT.
  • Authorization decides what that authenticated user can do, based on roles, permissions, and endpoint rules.
  • Failed authentication should return 401 because the request has no valid identity.
  • Failed authorization should return 403 because the authenticated identity lacks permission.

Configure Spring Security in Spring Boot

Step 1: Define users and roles

Model credentials and authorities clearly, and encode every stored password with BCryptPasswordEncoder.

Step 2: Configure authentication

Connect a UserDetailsService or authentication provider to the application's user source.

Step 3: Build the SecurityFilterChain

Declare public routes, require authentication by default, and place the JWT filter before UsernamePasswordAuthenticationFilter.

Step 4: Use stateless sessions

Set SessionCreationPolicy.STATELESS so each API request carries and validates its own token.

Step 5: Authorize endpoints by role

Apply request rules or method security such as hasRole and @PreAuthorize instead of manual role checks in controllers.

JWT Authentication Flow in Spring Boot

JWT (JSON Web Token) is commonly used for stateless authentication in Spring Boot APIs. After BCrypt verifies the submitted password, the server creates a signed, short-lived access token containing the user's identity and authorities.

The client sends that token as a Bearer credential on later requests. A security filter validates its signature and expiration, loads the authentication into the SecurityContext, and lets the authorization rules decide whether the endpoint is accessible. Refresh tokens should use a separate, revocable lifecycle rather than acting as long-lived access tokens.

Add spring-boot-starter-security to Your Project

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Common Spring Boot Security Mistakes

  • Putting role checks inside controllers or using broad permitAll rules
  • Hardcoding JWT secrets, committing credentials, or storing passwords without BCrypt
  • Issuing long-lived tokens without rotation or revocation
  • Using permissive CORS or incorrect CSRF settings and skipping forbidden or expired-token tests

SecurityFilterChain, Stateless Sessions, CORS, and CSRF

A modern SecurityFilterChain should state which routes are public, which require authentication, and which require a specific role. For JWT APIs, configure stateless session management and return consistent 401 responses for unauthenticated requests and 403 responses for authenticated users without permission. CORS controls which browser origins may call the API and should be limited to known clients. CSRF protection is commonly disabled for a stateless API that reads Bearer tokens from the Authorization header, but it remains important when authentication uses cookies. Make that choice from the credential transport model, not from a copied configuration snippet.

Start with AuthKit-Lite (Spring Boot JWT Authentication Boilerplate)

Skip repeated setup and use a reusable Spring Security and JWT foundation.

View Boilerplate

Free and open source

Frequently Asked Questions

What is JWT authentication in Spring Boot?

JWT authentication is a stateless way to secure APIs where tokens are used instead of sessions to verify users.

Should I use Spring Security for authentication?

Yes. Spring Security provides the filters and authorization infrastructure needed to implement JWT authentication and role-based access without writing an entire security framework.

Testing Secured Endpoints

Test public routes without a token, protected routes with valid and expired tokens, and role-restricted routes with both permitted and forbidden users. Spring Security test support can create mock users for authorization tests, while integration tests should exercise the real login and JWT filter flow. A complete security test suite also verifies invalid signatures, malformed headers, disabled users, CORS responses, and the expected 401 or 403 status. These tests keep security in Spring Boot reliable as endpoint rules and roles evolve.

Related BuildBaseKit Foundation

Apply the ideas in this guide with a focused Spring Boot authentication boilerplate, or learn how BuildBaseKit approaches a production-ready Spring Boot foundation.

Related articles

Guide Spring Boot Security 6 min read

Spring Boot JWT File Upload Security Guide

Learn how to secure file upload APIs in Spring Boot using JWT authentication, access control, upload validation, and secure file handling.