0
0
Spring Bootframework~5 mins

Securing endpoints by role in Spring Boot

Choose your learning style9 modes available
Introduction

We secure endpoints by role to control who can access certain parts of an application. This keeps data safe and ensures users only see what they should.

When you want only admins to access management pages.
When users should only see their own profile information.
When certain API endpoints should be restricted to specific user groups.
When you want to prevent unauthorized users from performing sensitive actions.
Syntax
Spring Boot
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/endpoint")
public ResponseEntity<String> method() {
    // method code
}
Use @PreAuthorize on controller methods to restrict access by role.
Roles usually start with 'ROLE_' prefix in Spring Security.
Examples
This endpoint is only accessible to users with the ADMIN role.
Spring Boot
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public String adminPage() {
    return "Admin content";
}
This endpoint allows users with USER or ADMIN roles to access it.
Spring Boot
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
@GetMapping("/dashboard")
public String dashboard() {
    return "Dashboard content";
}
This endpoint denies access to users with the GUEST role.
Spring Boot
@PreAuthorize("!hasRole('GUEST')")
@GetMapping("/secure")
public String secureArea() {
    return "Secure content";
}
Sample Program

This Spring Boot app has three endpoints. The /admin endpoint is only for ADMIN role users. The /user endpoint is only for USER role users. The /public endpoint is open to everyone.

Spring Boot
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class RoleSecurityApp {
    public static void main(String[] args) {
        SpringApplication.run(RoleSecurityApp.class, args);
    }
}

@RestController
class MyController {

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin")
    public String adminEndpoint() {
        return "Welcome Admin!";
    }

    @PreAuthorize("hasRole('USER')")
    @GetMapping("/user")
    public String userEndpoint() {
        return "Welcome User!";
    }

    @GetMapping("/public")
    public String publicEndpoint() {
        return "Welcome Guest!";
    }
}
OutputSuccess
Important Notes

Make sure to enable method security with @EnableMethodSecurity in your configuration.

Roles in Spring Security usually have the prefix 'ROLE_'. For example, 'ROLE_ADMIN'.

Test your endpoints with different user roles to confirm security works as expected.

Summary

Use @PreAuthorize to secure endpoints by user roles.

Roles control who can access specific parts of your app.

Always test security rules to keep your app safe.