Skip to main content

Spring Security Explained in Simple Words – JWT, OAuth2, Role-Based Access

Spring Security Explained in Simple Words – JWT, OAuth2, Role-Based Access


Introduction: Why Spring Security Matters

When you're building a real-world application in Java using Spring Boot, security is not optional. You want to make sure only the right users access the right features. That’s where Spring Security comes in.
But let’s be honest – most tutorials are too complex.

So, in this post, let’s simplify Spring Security — including JWT, OAuth2, and Role-Based Access Control (RBAC) — in plain language.


1. What is Spring Security?

Spring Security is a powerful and customizable framework for securing Java applications.

It provides:

  • Authentication: Who are you?
  • Authorization: What are you allowed to do?

It acts as a security filter in your application and works well with:

  • Spring MVC
  • Spring Boot
  • REST APIs


2. How Authentication Works in Spring Security

Let’s say a user tries to log in:

  1. The user submits a login request (username, password)
  2. Spring Security intercepts the request
  3. It checks if the credentials are valid (via UserDetailsService)
  4. If valid, it creates a Security Context and stores the user’s details

This all happens automatically if you configure Spring Security correctly.


3. Default Security – The Starting Point

When you add this dependency:

xml

Copy code

<dependency>

  <groupId>org.springframework.boot</groupId>

  <artifactId>spring-boot-starter-security</artifactId>

</dependency>

You instantly get:

  • A login form at /login
  • In-memory user (user) and a generated password
  • Basic Authentication for endpoints

You can override all of these with custom config.


4. Real-World Authentication: JWT Token-Based

In microservices and REST APIs, you can’t rely on session-based login.
That’s where JWT (JSON Web Token) comes in.

What is JWT?

JWT is a compact token that:

  • Contains user info (claims)
  • Is signed with a secret key
  • Is sent with every request (usually in the Authorization header)

Flow:

  1. User logs in → Server generates JWT
  2. Client stores the token (e.g. local storage)
  3. Every subsequent API request includes Authorization: Bearer <token>
  4. Server validates the token using secret key
  5. If valid, access is granted

Why JWT?

  • Stateless (no session on server)
  • Portable (can be used across services)
  • Scalable


5. Implementing JWT in Spring Boot (High Level)

You’ll need:

  • UsernamePasswordAuthenticationFilter: To handle login
  • JWTTokenProvider: To generate/validate tokens
  • SecurityConfig: To add JWT filter in the Spring Security filter chain

Example Snippet:

java

Copy code

http

  .csrf().disable()

  .authorizeRequests()

    .antMatchers("/auth/login").permitAll()

    .anyRequest().authenticated()

  .and()

  .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);


6. OAuth2 – For Third-Party Login (Google, GitHub, etc.)

What is OAuth2?

OAuth2 lets users log in using their existing accounts (e.g. Google, Facebook).

Flow:

  1. User clicks “Login with Google”
  2. Redirects to Google OAuth screen
  3. User approves
  4. Google sends authorization code to your app
  5. App exchanges code for access token
  6. You now know who the user is

In Spring Boot:

Just add:

xml

Copy code

<dependency>

  <groupId>org.springframework.boot</groupId>

  <artifactId>spring-boot-starter-oauth2-client</artifactId>

</dependency>

And in application.yml:

yaml

Copy code

spring:

  security:

    oauth2:

      client:

        registration:

          google:

            client-id: YOUR_ID

            client-secret: YOUR_SECRET

            redirect-uri: "{baseUrl}/login/oauth2/code/google"

Spring handles the rest.


7. Role-Based Access Control (RBAC)

What is RBAC?

RBAC means giving access based on user roles like:

  • ROLE_USER
  • ROLE_ADMIN
  • ROLE_MANAGER

Where is it used?

  • Only admins can delete users
  • Only HR can see salary info
  • Users can only see their own data

In Spring Security:

java

Copy code

@PreAuthorize("hasRole('ADMIN')")

public void deleteUser(Long id) {

   // only admin can delete

}

Or in config:

java

Copy code

http

  .authorizeRequests()

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

    .antMatchers("/user/**").hasAnyRole("USER", "ADMIN")

    .anyRequest().authenticated();


8. Custom UserDetailsService – Connecting to DB

Instead of hardcoded users, you can fetch from DB.

java

Copy code

@Service

public class CustomUserDetailsService implements UserDetailsService {

  @Autowired

  private UserRepository userRepo;


  @Override

  public UserDetails loadUserByUsername(String username) {

    User user = userRepo.findByUsername(username);

    return new org.springframework.security.core.userdetails.User(

      user.getUsername(), user.getPassword(), user.getRoles()

    );

  }

}


9. Common Mistakes to Avoid

  • Not disabling CSRF for APIs (csrf().disable())
  • Using session in microservices (use JWT instead)
  • Forgetting to hash passwords (BCryptPasswordEncoder)
  • Exposing sensitive endpoints publicly


Conclusion: Final Thoughts

Spring Security is one of the most powerful tools in the Java ecosystem — but only if you understand and simplify it.

Here’s what you should remember:

  • Use JWT for stateless REST APIs
  • Use OAuth2 for third-party login
  • Use RBAC to control access
  • Always plug in a custom UserDetailsService for real applications

Want code examples and step-by-step tutorials? Comment below and we’ll create a hands-on series soon!


URL Suggestion:

https://www.interviewyatra.com/2025/05/spring-security-jwt-oauth2-role-based.html

CTA:

✅ Bookmark this post for revision before interviews
✅ Share it with your Java dev friends
✅ Follow InterviewYatra.com for upcoming microservices series!


Comments

Popular posts from this blog

TCS Java Interview | Java | Spring Boot | Microservices | Database

TCS Java Interview | Java | Spring Boot | Microservices | Database This post is based on a Java backend developer interview simulation and provides direct transcript-based answers to help you prepare for similar interviews. 📺 This interview scenario was inspired by a video from the  YouTube channel:  CloudTech . 🔗 Watch the full video here:  https://www.youtube.com/watch?v=yVj2EgwZxk4 1. Can you introduce yourself and talk about your tech stack and domains? I have around 4.5 years of experience working as a Java developer. My core expertise is in Java and developing REST APIs using Spring Boot. I also have basic knowledge of microservices architecture. On the database side, I work with SQL and Oracle. Additionally, I have exposure to UI technologies like Angular, HTML, and CSS, but they are secondary skills. My primary focus is backend Java development. 2. Which version of Java are you currently working on? We are currently using Java 8 but are in the process of upgr...

Top 20 Spring Boot Microservices Architecture Interview Questions (With Speakable Answers)

Top 20 Spring Boot Microservices Architecture Interview Questions (With Speakable Answers) * * * 1. What is Microservices Architecture?   → Microservices architecture breaks an application into small, independent services. Each one handles a specific business function and can be developed, deployed, and scaled independently. They usually communicate over REST APIs or messaging queues. * * * 2. How does Spring Boot help in building microservices?   → Spring Boot offers embedded servers, auto-configuration, starter templates, and production-ready tools. It works well with Spring Cloud to provide service discovery, config management, load balancing, and more. * * * 3. What are the core components in a microservices setup?   → Key components include:   ✓ API Gateway   ✓ Eureka (Service Discovery)   ✓ Config Server   ✓ Kafka or RabbitMQ   ✓ Circuit Breaker (like Resilience4j)   ✓ Centralized logging and monitoring (ELK, Prometheus) * * * 4. What i...

Top 15 Spring Boot Interview Questions and Answers – Real Examples (2025)

Top 15 Spring Boot Interview Questions – 2025 Spring Boot is one of the most demanded frameworks for Java backend development. Whether you're interviewing for TCS, Infosys, or a product-based company, these Spring Boot questions will help you prepare like a pro. Here are 15 questions with detailed explanations for developers with 1–2 years of experience. Q1. What is Spring Boot? Answer: Spring Boot is a Java-based open-source framework built on top of the Spring Framework. It helps developers create stand-alone, production-ready Spring applications with minimal configuration. Its key features include: Auto-configuration Embedded servers (Tomcat, Jetty) Starter dependencies Production-ready tools (Actuator, Metrics, etc.) Example: You can create a REST API within minutes by using @RestController and spring-boot-starter-web — no need for external web server deployment. Q2. What is the role of @SpringBootApplication annotation? Answer: This annotation i...