Method security with @Secured Annotation in Spring
Tags: java, spring, springboot, tutorial
Published: 2024-07-11 21:21:59

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:

```java
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
```

### Annotating Methods with @Secured

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

```java
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.

```java
@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.

```xml
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

```

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. 

```java
@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!