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

Top 15 React Interview Questions for 1–2 Years Experience

🟦 Top 15 React Interview Questions for 1–2 Years Experience Preparing for a React interview with 1–2 years of experience? Here's a carefully curated list of 15 important React questions with clear, real-world answers. These are frequently asked in interviews at companies like TCS, Infosys, Cognizant, Capgemini, and product-based firms. Q1. What is the Virtual DOM in React, and how does it improve performance? Answer: The Virtual DOM is a lightweight, in-memory copy of the real DOM. When state/props change, React creates a new Virtual DOM tree, compares it with the old one (diffing), and only updates the parts of the real DOM that changed. This makes rendering much faster and improves performance in large applications. Q2. What is JSX in React? Answer: JSX stands for JavaScript XML. It allows us to write HTML elements in JavaScript and place them in the DOM without using createElement() . JSX improves code readability and is transpiled to React.createElement() calls. ...

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...

Wipro Java Developer Interview Questions with Answers (Mid-Level Role)

  Wipro Java Developer Interview Questions with Answers (Mid-Level Role) (Glassdoor Based – May 2024) Interview Location: Bengaluru Interview Mode: Online Candidate Role: Mid-Level Java Developer Source: Based on real experience shared on Glassdoor Review Summary: Easy and conversational. Interviewer was friendly. Focus was mainly on Java basics, internals, and real-world understanding. Q1: What is static in public static void main(String[] args) ? A: The static keyword lets the JVM call the method without creating an object. It indicates that the method belongs to the class, not instances. Q2: Why does a Java program start from the main method? A: main() is the predefined entry point of a Java application. The JVM starts execution from there. Q3: What are Checked and Unchecked Exceptions? With examples. A: Checked Exceptions : Detected at compile time. E.g., IOException , SQLException . Unchecked Exceptions : Detected at runtime. E.g., NullPointerExce...