"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Method security with @Secured Annotation in Spring

Method security with @Secured Annotation in Spring

Published on 2024-07-31
Browse:409

Method security with @Secured Annotation in Spring

This annotation provides a way to add security configuration to business methods.

It will use roles to check if a user has permission to call this method. The annotation is part of spring security. So to enable its usage you need the spring security dependency.

Example Scenario

You have an application that has a product CRUD. In this CRUD you want to control the operations using two specific roles.

  • User: can create the product and see the product. But cannot update or delete a product.
  • Admin: that can do all the user operations and can also update and delete a product.

You can use @Secured to manage the access of those roles on each operation.

Roles for Operations

We can define the following roles in our example scenario.

  • ROLE_USER, ROLE_ADMIN

To read:

  • ROLE_USER, ROLE_ADMIN

To update:

  • ROLE_ADMIN

To delete:

  • ROLE_ADMIN

Let's look at a code example and observe the application behavior.

Adding Spring Security Dependency

To work with the @Secured annotation, add the Maven dependency for Spring Security:


    org.springframework.boot
    spring-boot-starter-security

Annotating Methods with @Secured

We annotate the methods with @Secured defining which roles can access the method behavior.

public class Product {

    private Long id;
    private String name;
    private BigDecimal value;

    //getters and setters
}

@Service
public class ProductService {

    @Secured({"ROLE_USER", "ROLE_ADMIN"})
    public Product createProduct(Product product) {
        // Logic for creating a product
        return product;
    }

    @Secured({"ROLE_USER", "ROLE_ADMIN"})
    public Product getProductById(Long id) {
        // Logic for fetching a product
        return null;
    }

    @Secured("ROLE_ADMIN")
    public Product updateProduct(Product product) {
        // Logic for updating a product
        return product;
    }

    @Secured("ROLE_ADMIN")
    public void deleteProduct(Long id) {
        // Logic for deleting a product
    }
}

Application configuration

You need to add the @EnableGlobalMethodSecurity(securedEnabled = true) to configure your Spring application to use enable method security using @Secured.

@SpringBootApplication
@EnableTransactionManagement
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MasteryApplication {

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

}

Testing the Behavior

In our example we are going to test the behavior using tests, so we add the spring boot test dependency.


    org.springframework.security
    spring-security-test
    test


Then we create tests to validate if using a mock user and assign specific roles to him, we can test users in each role and how our application behaves. By doing that we can ensure that only the right roles can perform the allowed actions.

@SpringBootTest
class ProductServiceTests {

    @Autowired
    private ProductService productService;

    @Test
    @WithMockUser(roles = "USER")
    void testCreateProductAsUser() {
        Product product = new Product();
        assertDoesNotThrow(() -> productService.createProduct(product));
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void testCreateProductAsAdmin() {
        Product product = new Product();
        assertDoesNotThrow(() -> productService.createProduct(product));
    }

    @Test
    @WithAnonymousUser
    void testCreateProductAsAnonymous() {
        Product product = new Product();
        assertThrows(AccessDeniedException.class, () -> productService.createProduct(product));
    }

    @Test
    @WithMockUser(roles = "USER")
    void testGetProductByIdAsUser() {
        assertDoesNotThrow(() -> productService.getProductById(1L)); // Assuming product with ID 1 exists
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void testGetProductByIdAsAdmin() {
        assertDoesNotThrow(() -> productService.getProductById(1L));
    }

    @Test
    @WithAnonymousUser
    void testGetProductByIdAsAnonymous() {
        assertThrows(AccessDeniedException.class, () -> productService.getProductById(1L));
    }

    @Test
    @WithMockUser(roles = "USER")
    void testUpdateProductAsUser() {
        Product product = new Product();
        assertThrows(AccessDeniedException.class, () -> productService.updateProduct(product));
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void testUpdateProductAsAdmin() {
        Product product = new Product();
        assertDoesNotThrow(() -> productService.updateProduct(product));
    }

    @Test
    @WithAnonymousUser
    void testUpdateProductAsAnonymous() {
        Product product = new Product();
        assertThrows(AccessDeniedException.class, () -> productService.updateProduct(product));
    }

    @Test
    @WithMockUser(roles = "USER")
    void testDeleteProductAsUser() {
        assertThrows(AccessDeniedException.class, () -> productService.deleteProduct(1L));
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void testDeleteProductAsAdmin() {
        assertDoesNotThrow(() -> productService.deleteProduct(1L));
    }

    @Test
    @WithAnonymousUser
    void testDeleteProductAsAnonymous() {
        assertThrows(AccessDeniedException.class, () -> productService.deleteProduct(1L));
    }
}

That’s it, now you can manage user access to the application using roles with the @Secured annotation.

If you like this topic, make sure to follow me. In the following days, I’ll be explaining more about Spring annotations! Stay tuned!

Follow me!

Release Statement This article is reproduced at: https://dev.to/tiuwill/method-security-with-secured-annotation-in-spring-1hgk?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3