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

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

Recommended Posts

Powered by Blogger.