Here is an example (Code not tested !)
The methods you want to protect :
It can be controller methods :
@PreAuthorize("@userSecurityService.hasPaid()")
@RequestMapping(value = "/appointment", method = RequestMethod.GET)
public String appointment() {
//Some code
}
Or Service layer methods :
@PreAuthorize("@userSecurityService.hasPaid()")
@Transactional
public String appointment() {
//Some code
}
Or whatever :
@PreAuthorize("@userSecurityService.hasPaid()")
public String appointment() {
//Some code
}
The @Component
used for the validation :
@Component("userSecurityService")
public class UserSecurityService {
// You might want inject DAOs or other components for your validations.
@Inject
private UserDao userDao
public boolean hasPaid() {
// You might want access to user info from spring context.
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// Here you might want to use injected DAOs
// in order to validate the fact that the user had paid (or whatever).
// FIXME
return true;
}
}
Update (Thanks to @Pujan Srivastava comment) :
Spring AOP must be add as a dependency and the pre-post-annotations of Spring Security must be enabled :
Dependencies :
I personnaly use :
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
This gives me all the basic dependencies for Spring MVC and Spring Security to be properly configured in the Controller layer (and it includes Spring AOP).
So I only have to add spring-security-core dependency in the Service layer in order to protect services methods.
Enable pre-post-annotations :
Java config example :
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebMvcSecurityConfig extends WebSecurityConfigurerAdapter {
...
}
or with xml config like @Pujan Srivastava comment :
<sec:global-method-security pre-post-annotations="enabled" proxy-target-class="true"/>
in the dispatcher xml file.