Open In App

Spring Security Annotations

There are multiple annotations supported by Spring Security. But, in this article, we will discuss about these annotations can be used in a Spring Boot project as well. These annotations play a crucial role in creating a web application in Spring Boot. The Spring Security annotations are a powerful way to secure Spring applications. By using these annotations, you can control who has access to your application's resources and how they can interact with them.

Annotations

1. @Secured

@Secured({ "ROLE_ADMIN", "ROLE_SUPER_ADMIN" })
public void createUser(User user)
{
    // ... logic for create User
}

2. @PreAuthorize

@PreAuthorize("hasRole('ROLE_ADMIN')")
public void deleteAdminUser(Long userId)
{
    // ... logic for delete User
}

3. @PostAuthorize

@PostAuthorize(
    "hasRole('ROLE_ADMIN') and hasPermission(returnObject, 'read:courses')")
public List<Course>
findAllCourses()
{
    // ... logic for find all courses
}

4. @PreFilter

@PreFilter(
    "hasRole('ROLE_ADMIN') and hasPermission(filterObject, 'read:courses')")
public void
deleteCourses(List<Course> courses)
{
    // ... logic for delete Courses
}

5. @PostFilter

@PostFilter(
    "hasRole('ROLE_ADMIN') and hasPermission(filterObject, 'read:classes')")
public List<Class>
findAllClasses()
{
    // ...logic for find all classes
}

6. @RolesAllowed

@RolesAllowed("ROLE_ADMIN")
public void deleteCourse(Long courseId)
{
    // ... logic for delete course
}

7. @AuthenticationPrincipal

@GetMapping("/username")
public String getUsername(@AuthenticationPrincipal String username) {
  // ...
}

8. @RoleHierarchy

@RoleHierarchy(value = { "ROLE_ADMIN > ROLE_USER",
                         "ROLE_SUPER_ADMIN > ROLE_ADMIN" })

Conclusion

Spring Security provides a rich set of annotations to secure Spring MVC controllers, REST endpoints, and domain model methods. So in summary, annotations provide an elegant and declarative way to implement authorization and access control in Spring Security applications.

Article Tags :