Results for Spring Security

Top 25 Spring Security Interview Questions and Answers for Experienced Developers

10:07 PM

Spring Security is one of the most important frameworks in modern Java application development. Whether you are building REST APIs, microservices or enterprise applications, securing resources and controlling access is a critical requirement.


As a result, Spring Security questions frequently appear in technical interviews for Spring Boot developers, senior developers and solution architects.

This article covers the most commonly asked Spring Security interview questions along with detailed answers and practical explanations.


Who Should Read This Article?

  • Java Developers
  • Spring Boot Developers
  • Backend Engineers
  • Microservices Developers
  • Interview Candidates

1. What is Spring Security?

Spring Security is the official security framework provided by the Spring ecosystem. It offers a comprehensive set of features for authentication, authorization and protection against common security vulnerabilities.


Before Spring Security, developers often implemented authentication and authorization manually, which resulted in inconsistent security implementations and increased maintenance effort.


Spring Security standardizes application security and provides powerful capabilities such as:

  • Authentication
  • Authorization
  • Password Encoding
  • Session Management
  • CSRF Protection
  • JWT Integration
  • OAuth2 Support

Interview Tip: Mention that Spring Security is deeply integrated with Spring Boot and is the standard security framework used in enterprise Java applications.


2. What is Authentication?

Authentication is the process of verifying the identity of a user.

Authentication answers the question:


Who are you?

When a user submits credentials such as a username and password, Spring Security validates those credentials against a configured user store.

Only after successful verification is the user considered authenticated.

Examples of authentication mechanisms include:

  • Username and Password
  • JWT Authentication
  • OAuth2 Login
  • Single Sign-On (SSO)
  • Multi-Factor Authentication (MFA)

3. What is Authorization?

Authorization is the process of determining what an authenticated user is allowed to access.

Authorization answers the question:


What are you allowed to do?

For example, an ADMIN user may be allowed to delete records while a USER may only view data.

Authentication always occurs before authorization because the system must know the user's identity before assigning permissions.


4. What is the Difference Between Authentication and Authorization?

Authentication Authorization
Verifies Identity Verifies Permissions
Who Are You? What Can You Access?
Executed First Executed After Authentication

A simple way to remember:


Authentication
   ↓
Authorization

5. What is SecurityFilterChain?

SecurityFilterChain is the foundation of modern Spring Security configuration.

Every incoming request passes through a chain of security filters before reaching application controllers.


Client Request
      |
      v
SecurityFilterChain
      |
      v
Authentication
      |
      v
Authorization
      |
      v
Controller

The SecurityFilterChain is responsible for validating credentials, checking permissions and protecting application endpoints.


6. Why was WebSecurityConfigurerAdapter Deprecated?

Spring Security moved away from inheritance-based configuration in favour of bean-based configuration using SecurityFilterChain.

This approach is more flexible, easier to understand and aligns better with modern Spring Boot development practices.


7. What is UserDetailsService?

UserDetailsService is a Spring Security interface used to load user details during authentication.


UserDetailsService

When a user attempts to log in, Spring Security calls the UserDetailsService implementation to retrieve information about that user.


8. What is UserDetails?

UserDetails represents a security user inside Spring Security.

It contains information such as:

  • Username
  • Password
  • Roles
  • Authorities
  • Account Status

9. What is PasswordEncoder?

PasswordEncoder is used to securely encode passwords before storing them in a database.

Storing plain text passwords is a major security risk and should always be avoided.


10. Why is BCryptPasswordEncoder Commonly Used?

BCrypt is one of the most widely used password hashing algorithms because it generates secure hashes and automatically applies salting.

This makes password cracking significantly more difficult.


new BCryptPasswordEncoder()

11. What is JWT?

JWT stands for JSON Web Token. It is a compact and self-contained token used for stateless authentication. After successful login, the server generates a token and returns it to the client. The client includes the token in subsequent requests using the Authorization header.


Authorization:

Bearer eyJhbGciOi...

12. What are the Three Parts of JWT?

A JWT consists of three sections:


Header

Payload

Signature

The Header stores metadata, the Payload contains claims and the Signature protects token integrity.


13. Why is JWT Popular in REST APIs?

JWT supports stateless authentication.

The server does not need to maintain session information, making JWT ideal for cloud-native and microservice architectures.


14. What is Role-Based Access Control (RBAC)?

Role-Based Access Control restricts system access based on roles assigned to users.


ADMIN

MANAGER

USER

Each role receives specific permissions.


15. What is SecurityContext?

SecurityContext stores information about the currently authenticated user.

After authentication succeeds, Spring Security stores Authentication details inside the SecurityContext.


SecurityContextHolder
    .getContext()

16. What is CSRF?

CSRF (Cross-Site Request Forgery) is an attack where a malicious website tricks a user's browser into sending unwanted requests.

Spring Security provides built-in CSRF protection for web applications.


17. Why is CSRF Often Disabled for REST APIs?

Most REST APIs use stateless authentication with JWT instead of server-side sessions.

In those cases, CSRF protection is often disabled because session-based attacks are less relevant.


18. What is OncePerRequestFilter?

OncePerRequestFilter ensures a filter executes only once during request processing.

JWT validation filters commonly extend this class.


19. What is Method-Level Security?

Method-Level Security applies authorization rules directly to methods.


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

Only users with appropriate permissions can invoke the method.


20. What is the Difference Between 401 and 403?

Status Code Meaning
401 User is not authenticated
403 User is authenticated but lacks required permissions

21. What is OAuth2?

OAuth2 is an authorization framework that allows third-party applications to access resources on behalf of users without sharing passwords.

Examples include Google Login and GitHub Login.


22. What is Session Management?

Session management controls how user sessions are created, maintained and terminated.

Traditional applications commonly rely on sessions for authentication.


23. What is Stateless Authentication?

In stateless authentication, the server does not store session information.

Each request contains all required authentication information, typically through a JWT token.


24. What are Spring Security Filters?

Filters are components that process requests before they reach controllers.

Examples include:

  • Authentication Filter
  • Authorization Filter
  • JWT Filter
  • Logout Filter

25. Explain the Spring Security Request Lifecycle.


Client Request
      |
      v
SecurityFilterChain
      |
      v
Authentication
      |
      v
Authorization
      |
      v
Security Context
      |
      v
Controller

Every incoming request passes through this process before business logic is executed.


Recommended Spring Security Learning Path


Spring Security Basics
        ↓
Authentication vs Authorization
        ↓
RBAC
        ↓
SecurityFilterChain
        ↓
JWT Authentication
        ↓
OAuth2

Related Articles

  • Spring Security Explained for Beginners with Real Examples
  • Authentication vs Authorization in Spring Security
  • JWT Authentication in Spring Boot Explained with Real Examples
  • Role-Based Access Control (RBAC) in Spring Security
  • SecurityFilterChain in Spring Security Explained with Real Examples

Conclusion

Spring Security remains one of the most important frameworks in the Java ecosystem. Understanding Authentication, Authorization, JWT, RBAC, SecurityFilterChain and password encoding concepts is essential for building secure applications and performing well in Spring Security interviews.



Top 25 Spring Security Interview Questions and Answers for Experienced Developers Top 25 Spring Security Interview Questions and Answers for Experienced Developers Reviewed by 13thGhost on 10:07 PM Rating: 5

SecurityFilterChain in Spring Security Explained with Real Examples

9:57 PM

SecurityFilterChain is one of the most important concepts in modern Spring Security. Since Spring Security 5.7, SecurityFilterChain has become the recommended approach for defining security configurations.


Understanding SecurityFilterChain is essential for securing Spring Boot applications and frequently appears in Spring Security interviews.


What is SecurityFilterChain?

SecurityFilterChain is a sequence of security filters that process every incoming HTTP request before it reaches a controller.

Each filter performs a specific security task such as authentication, authorization or JWT validation.



Request
   |
   v
Security Filters
   |
   v
Controller

Why Do We Need SecurityFilterChain?

Without SecurityFilterChain, requests would directly reach application endpoints without security validation.

SecurityFilterChain acts as a security checkpoint.



Client
   |
   v
SecurityFilterChain
   |
   v
Protected API

Request Processing Flow


Client Request
       |
       v
Authentication Filter
       |
       v
Authorization Filter
       |
       v
Security Context
       |
       v
Controller

Every request must successfully pass through the chain.


Creating a SecurityFilterChain


@Bean

public SecurityFilterChain
securityFilterChain(
        HttpSecurity http)
throws Exception {

    http

        .authorizeHttpRequests(

            auth -> auth

                .anyRequest()
                .authenticated()

        )

        .formLogin();

    return http.build();

}

This configuration requires authentication for every endpoint.


Understanding HttpSecurity

HttpSecurity is used to configure web security rules.


HttpSecurity

It controls authentication, authorization, CORS, CSRF and session management.


Allowing Public Endpoints


.authorizeHttpRequests(

    auth -> auth

    .requestMatchers(
        "/public/**"
    )

    .permitAll()

)

Anyone can access these endpoints without authentication.


Securing Specific Endpoints


.authorizeHttpRequests(

    auth -> auth

    .requestMatchers(
        "/admin/**"
    )

    .hasRole("ADMIN")

)

Only ADMIN users can access those endpoints.


Multiple Security Rules


.authorizeHttpRequests(

    auth -> auth

        .requestMatchers(
            "/public/**"
        )

        .permitAll()

        .requestMatchers(
            "/admin/**"
        )

        .hasRole("ADMIN")

        .requestMatchers(
            "/manager/**"
        )

        .hasRole("MANAGER")

        .anyRequest()

        .authenticated()

)

Security Context

Spring Security stores authenticated user information inside SecurityContext.


SecurityContextHolder

Controllers and services can access the current authenticated user.


Accessing Current User


Authentication auth =

SecurityContextHolder
    .getContext()
    .getAuthentication();

This returns details about the currently logged-in user.


JWT and SecurityFilterChain

JWT authentication is implemented by adding a custom JWT filter into SecurityFilterChain.


JWT Token
     |
     v
JWT Filter
     |
     v
Security Context

This enables stateless authentication.


Disabling CSRF

REST APIs often disable CSRF protection.



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

This is common in JWT-based applications.


Common Filters in Spring Security

  • UsernamePasswordAuthenticationFilter
  • BasicAuthenticationFilter
  • JwtAuthenticationFilter
  • LogoutFilter
  • ExceptionTranslationFilter

SecurityFilterChain vs WebSecurityConfigurerAdapter

SecurityFilterChain WebSecurityConfigurerAdapter
Modern Approach Deprecated
Bean Based Inheritance Based
Spring Security 5.7+ Older Versions

Real World Example

An e-commerce platform may secure resources as follows:


/public/products

/admin/products

/admin/orders

/customer/orders

SecurityFilterChain determines who can access each endpoint.


Common Interview Questions

What is SecurityFilterChain?

It is a chain of security filters that process incoming requests before controllers are invoked.


Why was WebSecurityConfigurerAdapter removed?

Spring Security moved to a bean-based configuration model using SecurityFilterChain.


Can SecurityFilterChain work with JWT?

Yes. JWT validation is commonly implemented through custom filters.


What is HttpSecurity?

A configuration object used to define security rules.


What is SecurityContext?

A container that stores information about the authenticated user.


Best Practices

  • Use SecurityFilterChain instead of deprecated approaches.
  • Keep security rules simple and clear.
  • Use role-based authorization.
  • Protect sensitive endpoints.
  • Combine with JWT for REST APIs.

Frequently Asked Questions (FAQ)

Can multiple SecurityFilterChain beans exist?

Yes. Applications can define multiple security configurations.


Can SecurityFilterChain secure REST APIs?

Yes. It is commonly used in modern Spring Boot API security.


Should SecurityFilterChain be used with JWT?

Yes. This is a common modern security architecture.


Conclusion

SecurityFilterChain is the foundation of modern Spring Security. It processes incoming requests, performs authentication and authorization checks, and protects application resources. Understanding SecurityFilterChain is essential for building secure Spring Boot applications and succeeding in Spring Security interviews.


Keywords

SecurityFilterChain, Spring Security Filter Chain, Spring Boot Security, Spring Security Configuration, HttpSecurity, Spring Security Tutorial, JWT SecurityFilterChain, Spring Security Interview Questions, Authorization Filter, Authentication Filter, Spring Boot Authentication, Spring Boot Authorization, Java Security, Enterprise Application Security, Spring Security Architecture

SecurityFilterChain in Spring Security Explained with Real Examples SecurityFilterChain in Spring Security Explained with Real Examples Reviewed by 13thGhost on 9:57 PM Rating: 5

Role-Based Access Control (RBAC) in Spring Security with Real Examples

12:44 PM

Authentication verifies who a user is, but authentication alone is not enough. Enterprise applications must also control what users are allowed to access.


Role-Based Access Control (RBAC) is one of the most widely used authorization models in Spring Security. It allows applications to restrict access based on user roles.


What is RBAC?

RBAC stands for Role-Based Access Control.

Users are assigned roles, and roles determine what resources users can access.


User
   |
   v
Role
   |
   v
Permissions

Why Do We Need RBAC?

Consider an e-commerce application.


Customer

Manager

Administrator

Each type of user requires different access privileges.

Without RBAC, every authenticated user would have the same permissions.


Real World Example


ADMIN

Manage Users

Delete Users

View Reports

Manage Products


MANAGER

Manage Products

View Reports


USER

View Products

Place Orders

Each role has its own set of permissions.


Spring Security Role Format

Spring Security internally stores roles using the ROLE_ prefix.


ROLE_ADMIN

ROLE_MANAGER

ROLE_USER

Developers typically specify roles without the prefix.


.roles("ADMIN")

Create Users with Roles


@Bean

public UserDetailsService
userDetailsService() {

    UserDetails admin =

        User.builder()

            .username("admin")

            .password(
                passwordEncoder()
                    .encode("admin123")
            )

            .roles("ADMIN")

            .build();

    UserDetails user =

        User.builder()

            .username("user")

            .password(
                passwordEncoder()
                    .encode("user123")
            )

            .roles("USER")

            .build();

    return new
        InMemoryUserDetailsManager(
            admin,
            user
        );
}

Secure Endpoints Using Roles


@Bean

public SecurityFilterChain
securityFilterChain(
    HttpSecurity http
)
throws Exception {

    http

    .authorizeHttpRequests(

        auth -> auth

            .requestMatchers(
                "/admin/**"
            )

            .hasRole("ADMIN")

            .requestMatchers(
                "/user/**"
            )

            .hasRole("USER")

            .anyRequest()

            .authenticated()

    );

    return http.build();
}

Spring Security automatically checks roles before allowing access.


Example Controller


@RestController

@RequestMapping("/admin")

public class AdminController {

    @GetMapping("/reports")

    public String reports() {

        return "Admin Reports";

    }

}

Only ADMIN users can access this endpoint.


Access Control Flow


Request
   |
   v
Authentication
   |
   v
Role Check
   |
   +------ Access Granted

   |
   +------ Access Denied

Using Multiple Roles

Some endpoints may allow access to multiple roles.


.hasAnyRole(

    "ADMIN",

    "MANAGER"

)

Both ADMIN and MANAGER users can access the resource.


Method Level Security

RBAC can be applied directly to methods.



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

public void deleteUser() {

}

Spring Security verifies permissions before executing the method.


Role Hierarchy Example


ADMIN
   |
   +---- MANAGER
            |
            +---- USER

Higher roles can inherit permissions from lower roles.


Authentication vs RBAC

Authentication RBAC
Who Are You? What Can You Access?
Login Verification Permission Verification
User Identity User Access Control

HTTP Response Codes

401 Unauthorized

User is not authenticated.


403 Forbidden

User is authenticated but lacks permission.


Common Interview Questions

What is RBAC?

Role-Based Access Control restricts access based on assigned user roles.


What is the difference between Authentication and Authorization?

Authentication verifies identity. Authorization determines permissions.


What does hasRole() do?

It restricts access to users possessing a specific role.


What does hasAnyRole() do?

It allows access to multiple role types.


What is the meaning of 403 Forbidden?

The user is authenticated but lacks sufficient permissions.


Best Practices

  • Follow the principle of least privilege.
  • Avoid assigning excessive permissions.
  • Implement role hierarchies carefully.
  • Use method-level security where appropriate.
  • Test role-based authorization thoroughly.

Frequently Asked Questions (FAQ)

Can a user have multiple roles?

Yes. Spring Security supports multiple roles per user.


Can RBAC be used with JWT?

Yes. JWT claims commonly contain user roles.


Is RBAC used in enterprise applications?

Yes. RBAC is one of the most widely adopted authorization models.


Conclusion

Role-Based Access Control is a critical part of Spring Security. By assigning roles and limiting access based on permissions, developers can secure sensitive application functionality and implement scalable authorization mechanisms in enterprise applications.


Keywords

RBAC Spring Security, Role Based Access Control, Spring Security Roles, Spring Security Authorization, hasRole Example, hasAnyRole Example, Spring Security RBAC, Spring Boot Security, Role Hierarchy Spring Security, Authorization Example, Security Interview Questions, Java Security, Enterprise Security, Spring Boot Authorization, Spring Security Tutorial


Role-Based Access Control (RBAC) in Spring Security with Real Examples Role-Based Access Control (RBAC) in Spring Security with Real Examples Reviewed by 13thGhost on 12:44 PM Rating: 5

JWT Authentication in Spring Boot Explained with Real Examples

12:36 PM

Modern applications are increasingly built using REST APIs and microservices. Traditional session-based authentication is often not suitable for these architectures.


JWT (JSON Web Token) is one of the most popular solutions for securing REST APIs and is widely used in Spring Boot applications.


What is JWT?

JWT stands for JSON Web Token. It is a compact and self-contained token used to securely transmit user information between client and server.

After successful authentication, the server generates a JWT token and returns it to the client.


Why Do We Need JWT?

Consider a REST API accessed by mobile applications, web applications and third-party clients.

Using HTTP sessions becomes difficult because the server must maintain session information.

JWT solves this problem by storing user information inside the token itself.


JWT Authentication Flow


User Login
     |
     v
Authentication
     |
     v
Generate JWT
     |
     v
Return JWT
     |
     v
Store JWT
     |
     v
Send JWT with Requests
     |
     v
Validate JWT
     |
     v
Access Protected APIs

Real World Example

A customer logs into an e-commerce application.


Username:
john

Password:
password123

Credentials are validated successfully.

Spring Boot generates a JWT token.


eyJhbGciOiJIUzI1NiJ9...

The client stores this token and uses it for future requests.


JWT Structure

A JWT token contains three parts.


Header

Payload

Signature

Example


xxxxx.yyyyy.zzzzz

Header

The header contains token metadata.


{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

The payload contains claims.


{
  "sub": "john",
  "role": "USER"
}

This is where user-related data is stored.


Signature

The signature ensures token integrity.

If the token is modified, signature validation fails.


Add Required Dependency


<dependency>
    <groupId>
        io.jsonwebtoken
    </groupId>

    <artifactId>
        jjwt-api
    </artifactId>

    <version>
        0.11.5
    </version>
</dependency>

Generating JWT Token


public String generateToken(
        String username) {

    return Jwts.builder()

        .setSubject(username)

        .setIssuedAt(
            new Date()
        )

        .setExpiration(
            new Date(
                System.currentTimeMillis()
                + 86400000
            )
        )

        .signWith(
            SECRET_KEY
        )

        .compact();
}

This creates a token valid for 24 hours.


Validating JWT Token


public boolean validateToken(
        String token) {

    try {

        Jwts.parserBuilder()

            .setSigningKey(
                SECRET_KEY
            )

            .build()

            .parseClaimsJws(
                token
            );

        return true;

    }
    catch(Exception ex) {

        return false;

    }
}

Sending JWT in Requests

JWT is usually sent using the Authorization header.


Authorization:

Bearer
eyJhbGciOiJIUzI1NiJ9...

Spring Security JWT Flow


Client
   |
   v
JWT Filter
   |
   v
Validate Token
   |
   v
Security Context
   |
   v
Controller

Every request passes through a JWT filter before reaching the controller.


JWT Filter Example


public class JwtAuthenticationFilter
extends OncePerRequestFilter {

}

This filter extracts and validates the JWT token.


Benefits of JWT

  • Stateless Authentication
  • Scalable Architecture
  • Microservices Friendly
  • Reduced Server Memory Usage
  • Widely Supported

Limitations of JWT

  • Token Revocation Complexity
  • Payload Visibility
  • Larger Request Size
  • Secret Key Management Required

JWT vs Session-Based Authentication

JWT Session
Stateless Stateful
Scalable Requires Session Storage
API Friendly Web Applications
Popular for Microservices Traditional Applications

Common Interview Questions

What is JWT?

A JSON Web Token used for secure authentication and authorization.


What are the three parts of JWT?

Header, Payload and Signature.


Is JWT encrypted?

No. JWT is encoded and signed, not encrypted by default.


Why use JWT in REST APIs?

Because it provides stateless authentication and good scalability.


Where is JWT stored?

Typically inside local storage, session storage or HTTP-only cookies.


Best Practices

  • Keep token expiration short.
  • Use HTTPS.
  • Never store sensitive information in payload.
  • Protect secret keys.
  • Implement refresh token strategy.

Frequently Asked Questions (FAQ)

Can JWT contain roles?

Yes. Roles and permissions can be included in claims.


Can JWT be used with Spring Security?

Yes. Spring Security commonly integrates with JWT authentication.


Is JWT suitable for microservices?

Yes. JWT is widely used in microservice architectures.


Conclusion

JWT Authentication has become the standard approach for securing REST APIs and microservices. Understanding token generation, validation, filters, claims and SecurityContext integration is essential for building secure Spring Boot applications and succeeding in modern Java interviews.


Keywords

JWT Authentication, Spring Boot JWT, Spring Security JWT, JSON Web Token, JWT Tutorial, JWT Interview Questions, Spring Boot Security, JWT Filter, Stateless Authentication, JWT Authentication Example, REST API Security, Microservices Security, Spring Security Tutorial, Java Backend Security, Enterprise Java Development



JWT Authentication in Spring Boot Explained with Real Examples JWT Authentication in Spring Boot Explained with Real Examples Reviewed by 13thGhost on 12:36 PM Rating: 5

Authentication vs Authorization in Spring Security with Real Examples

12:27 PM

Authentication and Authorization are two fundamental security concepts that every Spring Boot developer must understand.


Although these terms are often used together, they solve different security challenges inside an application.

Understanding this difference is a common requirement in Spring Security interviews and real-world enterprise projects.


What is Authentication?

Authentication is the process of verifying the identity of a user.

Authentication answers the question:


Who are you?

The system validates the credentials supplied by the user.

Example


Username:
john

Password:
secret123

Spring Security verifies whether these credentials are correct.


Real World Authentication Example

Consider internet banking.

Before accessing an account, the user must log in.



Enter Username
       +
Enter Password
       |
       v
Identity Verified

This process is Authentication.


What is Authorization?

Authorization determines what an authenticated user is allowed to do.

Authorization answers the question:


What are you allowed to access?

After identity verification, Spring Security evaluates permissions and roles.


Real World Authorization Example


ADMIN
   |
   +---- Create User

   +---- Delete User

   +---- View Reports

USER
   |
   +---- View Profile

   +---- Update Profile

Both users are authenticated.

However, their permissions differ.


Authentication vs Authorization

Authentication Authorization
Verifies Identity Verifies Permissions
Who Are You? What Can You Do?
Occurs First Occurs After Authentication
Username & Password Roles & Permissions

Spring Security Flow


User Request
      |
      v
Authentication
      |
      v
Authorization
      |
      v
Protected Resource

Authentication always occurs before authorization.


Authentication Example in Spring Security


@Bean

public UserDetailsService
userDetailsService() {

    UserDetails user =

        User.builder()

            .username("john")

            .password(
                passwordEncoder()
                .encode("password")
            )

            .roles("USER")

            .build();

    return new InMemoryUserDetailsManager(
        user
    );

}

Spring Security authenticates users using stored credentials.


Authorization Example in Spring Security


.authorizeHttpRequests(

    auth -> auth

        .requestMatchers(
            "/admin/**"
        )

        .hasRole("ADMIN")

)

Only users with ADMIN role can access admin endpoints.


Scenario 1: Successful Authentication


Username: admin

Password: admin123

Credentials match.

User is authenticated successfully.


Scenario 2: Failed Authentication


Username: admin

Password: wrongPassword

Credentials do not match.

Access is denied immediately.

Authorization never occurs.


Scenario 3: Authorization Failure

Suppose a USER attempts to access an ADMIN endpoint.


Role:
USER

Request:
GET /admin/users

Authentication succeeds.

Authorization fails.

Spring Security returns:


403 Forbidden

Role-Based Authorization

Spring Security commonly uses roles.


ROLE_ADMIN

ROLE_MANAGER

ROLE_USER

Each role receives different permissions.


Method Level Authorization

Authorization can be applied at method level.



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

public void deleteUser() {

}

Only ADMIN users can execute this method.


Authentication Mechanisms

Common authentication methods include:


  • Username and Password
  • JWT Authentication
  • OAuth2
  • Single Sign-On (SSO)
  • Multi-Factor Authentication

Authorization Models

  • Role-Based Access Control (RBAC)
  • Permission-Based Access
  • Attribute-Based Access Control

Real World Example

Consider an e-commerce application.



Customer
      |
      +---- View Products

      +---- Place Orders

Admin
      |
      +---- Manage Products

      +---- Manage Orders

      +---- View Reports

Authentication identifies the user.

Authorization controls accessible features.


Common Interview Questions

What is Authentication?

Authentication verifies the identity of a user.


What is Authorization?

Authorization determines what actions a user can perform.


Which comes first?

Authentication always occurs before Authorization.


What HTTP status code indicates authorization failure?

403 Forbidden.


Can Authorization occur without Authentication?

Generally no. The user's identity must be verified first.


Best Practices

  • Always authenticate users before granting access.
  • Follow least privilege principles.
  • Use role-based security.
  • Encrypt passwords using BCrypt.
  • Protect sensitive endpoints.

Frequently Asked Questions (FAQ)

Can multiple roles be assigned to a user?

Yes. A user may have multiple roles and permissions.


Is JWT Authentication or Authorization?

JWT primarily supports Authentication but can also carry authorization information such as roles.


Do all applications require Authorization?

Most enterprise applications require authorization to protect resources.


Conclusion

Authentication and Authorization are core security concepts in Spring Security. Authentication verifies identity while Authorization determines permissions. Understanding the difference between these concepts is essential for designing secure applications and succeeding in Spring Security interviews.


Keywords

Authentication vs Authorization, Spring Security Authentication, Spring Security Authorization, Spring Boot Security, RBAC Spring Security, Security Interview Questions, Spring Security Tutorial, Role Based Access Control, Authentication Example, Authorization Example, Spring Boot Authentication, Spring Boot Authorization, SecurityFilterChain, Java Security, Enterprise Application Security

Authentication vs Authorization in Spring Security with Real Examples Authentication vs Authorization in Spring Security with Real Examples Reviewed by 13thGhost on 12:27 PM Rating: 5

Spring Security Explained for Beginners with Real Examples

12:19 PM

Security is one of the most important requirements of modern web applications. Without proper security controls, unauthorized users may access sensitive information and business functionality.


Spring Security is the official security framework for Spring applications that provides authentication, authorization and protection against common security threats.


What is Spring Security?

Spring Security is a framework that helps secure Spring applications.

It provides:

  • Authentication
  • Authorization
  • Password Protection
  • CSRF Protection
  • Session Management
  • Role-Based Access Control

Why Do We Need Spring Security?

Imagine an online banking application.

Without security:



Anyone
      |
      v
View Accounts

Transfer Money

Access Customer Data

Clearly this is dangerous.

Spring Security ensures only authorised users can access sensitive resources.


Authentication vs Authorization

These terms are frequently confused.


Authentication

Authentication answers:


Who are you?

Example:



Username:
admin

Password:
secret123

Spring verifies the identity of the user.


Authorization

Authorization answers:


What are you allowed to do?

Example:



ADMIN
    |
    +---- Create User

    +---- Delete User

USER
    |
    +---- View Profile

After authentication, Spring determines permissions.


Spring Security Flow


User Request
      |
      v
Security Filter Chain
      |
      v
Authentication
      |
      v
Authorization
      |
      v
Controller

Every incoming request passes through Spring Security.


Add Spring Security Dependency

Add the following dependency to pom.xml.



<dependency>

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

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

</dependency>

What Happens After Adding Dependency?

Spring Boot automatically secures all endpoints.

When you start the application, a generated password appears in the console.



Using generated security password:

8c3f1c9d-xxxx-yyyy-zzzz

This default user can access the application.


Securing an API


@RestController

@RequestMapping("/api")
public class EmployeeController {

    @GetMapping("/employees")
    public String employees() {

        return "Employees Data";

    }
}

After adding Spring Security, authentication is required automatically.


Configure In-Memory Users


@Bean

public UserDetailsService
userDetailsService() {

    UserDetails admin =

        User.builder()

            .username("admin")

            .password(
                passwordEncoder()
                    .encode("admin123")
            )

            .roles("ADMIN")

            .build();

    return new InMemoryUserDetailsManager(
        admin
    );
}

This creates a simple in-memory administrator account.


Password Encoding

Passwords should never be stored as plain text.



@Bean

public PasswordEncoder
passwordEncoder() {

    return new BCryptPasswordEncoder();

}

BCrypt is one of the most commonly used password encoders.


Role-Based Security

Spring Security supports roles.


ADMIN

USER

MANAGER

Endpoints can be restricted to specific roles.


.authorizeHttpRequests(

    auth -> auth

        .requestMatchers(
            "/admin/**"
        )

        .hasRole("ADMIN")

)

Only ADMIN users can access those endpoints.


SecurityFilterChain Configuration


@Bean

public SecurityFilterChain
securityFilterChain(
    HttpSecurity http
) throws Exception {

    http

        .authorizeHttpRequests(

            auth -> auth

                .anyRequest()

                .authenticated()

        )

        .formLogin();

    return http.build();

}

This tells Spring Security to require authentication for all requests.


Common Security Features

  • Authentication
  • Authorization
  • Password Encryption
  • Session Management
  • CSRF Protection
  • Role Management

Real World Example

Consider an e-commerce application.



Customer
      |
      +---- View Products

Admin
      |
      +---- Add Products

      +---- Remove Products

      +---- Manage Orders

Different users have different access levels.

Spring Security manages these permissions.


Common Interview Questions

What is Spring Security?

A framework that provides authentication and authorization for Spring applications.


What is Authentication?

Authentication verifies the identity of a user.


What is Authorization?

Authorization determines what a user is allowed to do.


What is SecurityFilterChain?

A component that defines security rules for incoming requests.


Why use BCryptPasswordEncoder?

To securely store encrypted passwords instead of plain text passwords.


Best Practices

  • Always encrypt passwords.
  • Use role-based access control.
  • Never store passwords in plain text.
  • Secure sensitive endpoints.
  • Apply the principle of least privilege.

Frequently Asked Questions (FAQ)

Does Spring Boot provide Security automatically?

Yes. Adding Spring Security dependency automatically secures endpoints.


Can Spring Security work with JWT?

Yes. JWT is commonly used in modern REST APIs.


Can Spring Security secure REST APIs?

Yes. It is widely used to secure RESTful applications.


Conclusion

Spring Security is the standard framework for securing Spring Boot applications. Understanding Authentication, Authorization, SecurityFilterChain, Password Encoding and Role-Based Access Control provides a strong foundation for building secure enterprise applications.


Keywords

Spring Security Tutorial, Spring Security Basics, Spring Boot Security, Authentication vs Authorization, SecurityFilterChain, BCryptPasswordEncoder, Spring Boot Authentication, Spring Boot Authorization, Spring Security Interview Questions, Spring Boot REST Security, Role Based Access Control, Secure Spring Boot APIs, Java Backend Security, Spring Framework Security, Enterprise Java Security

Spring Security Explained for Beginners with Real Examples Spring Security Explained for Beginners with Real Examples Reviewed by 13thGhost on 12:19 PM Rating: 5

Recommended Posts

Powered by Blogger.