Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 43

    Role-Based Access Control

    RBAC assigns permissions to roles, and roles to users.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    RBAC assigns permissions to roles, and roles to users. In Orders: USER places and views own orders; ADMIN manages catalog and refunds; SUPPORT may read but not price-override.

    Spring Security models roles as authorities, conventionally prefixed with ROLE_. hasRole('ADMIN') looks for ROLE_ADMIN. Store roles in normalized tables — not CSV strings on the user row.

    RBAC is coarse. Owner checks ('only the customer who placed the order') still need SpEL or service-level comparisons. When rules explode into per-field policies, consider ABAC or a policy engine later.

    This lesson wires roles into Authentication and URL/method checks for TechLearningPRO Orders.

    Purpose of this lesson

    Model Orders roles in the user store and enforce them with hasRole / authorities consistently.

    Understanding the topic

    Users ↔ roles ↔ allowed operations.

    • Role: named set of capabilities (USER, ADMIN, SUPPORT).
    • Authority: Spring's granted privilege string (ROLE_ADMIN).
    • Many-to-many: users can hold multiple roles.
    • hasRole vs hasAuthority: know the ROLE_ prefix convention.
    • Assignment: role grants are privileged, audited operations.

    Step-by-step explanation

    1. Create roles and user_roles tables (or equivalent entities).
    2. Map roles to SimpleGrantedAuthority in UserDetailsService.
    3. Protect admin Orders routes with hasRole('ADMIN').
    4. Verify a USER cannot hit admin refund endpoints.

    Informative example

    Schema sketch and enforcement.

    java
    -- roles
    -- id | name
    -- 1 | USER
    -- 2 | ADMIN
    -- user_roles
    -- user_id | role_id
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/api/admin/orders/{id}")
    public void adminDelete(@PathVariable long id) {
    orders.adminDelete(id);
    }
    // UserDetails authorities
    u.getRoles().stream()
    .map(r -> new SimpleGrantedAuthority("ROLE_" + r))
    .toList();

    Real-world use

    TechLearningPRO initially stuffed roles into a comma-separated column. A typo created ADMIM, and a support engineer lost access mid-incident. Normalized role rows plus a seed migration made grants reviewable and prevented silent string drift.

    Security implications

    Privilege escalation is the RBAC failure mode.

    • Only audited admin tools assign roles.
    • Remove roles immediately on offboarding.
    • Do not embed role decisions only in the SPA router.

    Best practices

    • Keep a small, documented role set; add roles deliberately.
    • Seed roles via migrations; do not hard-code magic strings across dozens of classes.
    • Combine RBAC with resource ownership for customer data.

    Common mistakes

    • Double-prefixing ROLE_ROLE_ADMIN by adding ROLE_ in both DB and code.
    • Granting ADMIN in JWT claims without verifying those claims against the user store when freshness matters.
    • Using roles for per-order ownership instead of explicit owner checks.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat is RBAC?+

    Answer

    A model where permissions are granted to roles and users receive roles, simplifying access management.
    2IntermediateQuestionhasRole('ADMIN') looks for which authority?+

    Answer

    Typically ROLE_ADMIN because Spring adds the ROLE_ prefix for role checks.
    3IntermediateQuestionWhen is RBAC not enough?+

    Answer

    When decisions depend on resource attributes (ownership, region, clearance) — then ABAC or policy engines help.

    Hands-on exercise

    Lab. Create USER and ADMIN accounts. Confirm ADMIN can call refund; USER receives 403. Attempt to forge an ADMIN role claim if you control a test JWT issuer and show why signature verification still matters.

    Summary

    RBAC gives Orders a clear privilege vocabulary. Next: hashing passwords correctly with PasswordEncoder.

    Ready to mark this lesson complete?Track your journey across the entire course.