Spring Security - Method Security

Method Security

Method Security

Enable method security using @EnableGlobalMethodSecurity annotation

1
2
3
4
5
6
7
8
9
10
11
12
@SpringBootApplication
@EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true
)
public class SpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
}
}

Now you can use @Secured annotation to specify the roles needed to access the method

1
2
3
4
5
6
7
8
@Service
public class MyService {
@Secured("ROLE_ADMIN")
public String getSecretMessage() {
return "secret test";
}
}

The @RoleAllowed annotation is the JSR-250’s equivalent annotation of the @Secured annotation. You can swap @Secured with @RolesAllowed annotaiton and it will still work.

1
@RolesAllowed("ROLE_ADMIN")

@PreAuthorize and @PostAuthorize

@PreAuthorize and @PostAuthorize allows you to use SpEL expression access control. @PreAuthorize happens before method invocation. @PostAuthorize happens after method invocation.

1
2
3
4
@PreAuthorize("hasRole('ADMIN')")
public String getSecretMessage() {
return "secret test";
}

Expression-based annotations are a good choice if you need to define simple rules that go beyond checking the role names against the user’s list of authorities.

Reference