Introduction
Role-based access control helps decide who can do what in an app. It keeps things safe by giving permissions based on user roles.
Jump into concepts and practice - no test required
Role-based access control helps decide who can do what in an app. It keeps things safe by giving permissions based on user roles.
@PreAuthorize("hasRole('ROLE_NAME')")
public ReturnType methodName() {
// method code
}@PreAuthorize("hasRole('ADMIN')") public String adminOnly() { return "Admin content"; }
@PreAuthorize("hasAnyRole('USER', 'ADMIN')") public String userOrAdmin() { return "User or Admin content"; }
@PreAuthorize("!hasRole('GUEST')") public String noGuest() { return "Not for guests"; }
This Spring Boot app has three endpoints. The '/admin' endpoint is only for ADMIN role users. The '/user' endpoint is for USER or ADMIN roles. The '/public' endpoint is open to all.
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @EnableMethodSecurity public class RbacDemoApplication { public static void main(String[] args) { SpringApplication.run(RbacDemoApplication.class, args); } } @RestController class DemoController { @GetMapping("/admin") @PreAuthorize("hasRole('ADMIN')") public String adminAccess() { return "Welcome Admin!"; } @GetMapping("/user") @PreAuthorize("hasAnyRole('USER', 'ADMIN')") public String userAccess() { return "Welcome User or Admin!"; } @GetMapping("/public") public String publicAccess() { return "Welcome Everyone!"; } }
Make sure to enable method security with @EnableMethodSecurity in your config.
Roles are case-sensitive and usually prefixed with 'ROLE_'.
Access denied errors return HTTP 403 status by default.
Role-based access control restricts access based on user roles.
Use @PreAuthorize annotations on methods to enforce role checks.
Configure roles carefully to protect sensitive parts of your app.
@PreAuthorize("hasRole('ADMIN')"), what will happen if a user with role USER tries to access this method?@PreAuthorize("hasRole('ADMIN')")
public String adminPage() {
return "Welcome Admin";
}@PreAuthorize expression correctly enforces this?