0
# Core Security Annotations
1
2
Spring Security Config provides several key annotations that enable and configure security features in Spring applications. These annotations serve as entry points to the security configuration system and automatically import necessary configuration classes.
3
4
## Web Security Annotations
5
6
### @EnableWebSecurity
7
8
The primary annotation for enabling Spring Security web security configuration.
9
10
```java { .api }
11
@Target(ElementType.TYPE)
12
@Retention(RetentionPolicy.RUNTIME)
13
@Documented
14
@Import({WebSecurityConfiguration.class, SpringWebMvcImportSelector.class,
15
OAuth2ImportSelector.class, HttpSecurityConfiguration.class})
16
@EnableGlobalAuthentication
17
public @interface EnableWebSecurity {
18
/**
19
* Controls debugging support for Spring Security.
20
* @return true if debugging is enabled, false otherwise. Default is false.
21
*/
22
boolean debug() default false;
23
}
24
```
25
26
This annotation:
27
- Imports essential Spring Security configuration classes
28
- Enables web security filter chain processing
29
- Automatically configures security infrastructure
30
- Provides optional debug mode for troubleshooting
31
32
**Usage Example:**
33
34
```java
35
@Configuration
36
@EnableWebSecurity
37
public class SecurityConfig {
38
39
@Bean
40
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
41
return http
42
.authorizeHttpRequests(authz -> authz.anyRequest().authenticated())
43
.formLogin(Customizer.withDefaults())
44
.build();
45
}
46
}
47
```
48
49
### @EnableGlobalAuthentication
50
51
Enables global authentication configuration capabilities.
52
53
```java { .api }
54
@Target(ElementType.TYPE)
55
@Retention(RetentionPolicy.RUNTIME)
56
@Documented
57
@Import(AuthenticationConfiguration.class)
58
public @interface EnableGlobalAuthentication {
59
}
60
```
61
62
This annotation is typically used internally by other security annotations but can be used independently to enable authentication infrastructure.
63
64
## Method Security Annotations
65
66
### @EnableMethodSecurity
67
68
Modern method-level security configuration annotation (Spring Security 5.6+).
69
70
```java { .api }
71
@Target(ElementType.TYPE)
72
@Retention(RetentionPolicy.RUNTIME)
73
@Documented
74
@Import(MethodSecurityConfiguration.class)
75
public @interface EnableMethodSecurity {
76
/**
77
* Determines if Spring Security's pre/post annotations should be enabled.
78
* @return true if pre/post annotations are enabled, false otherwise. Default is true.
79
*/
80
boolean prePostEnabled() default true;
81
82
/**
83
* Determines if Spring Security's @Secured annotation should be enabled.
84
* @return true if @Secured is enabled, false otherwise. Default is false.
85
*/
86
boolean securedEnabled() default false;
87
88
/**
89
* Determines if JSR-250 annotations should be enabled.
90
* @return true if JSR-250 annotations are enabled, false otherwise. Default is false.
91
*/
92
boolean jsr250Enabled() default false;
93
94
/**
95
* Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
96
* to standard Java interface-based proxies.
97
* @return true to use CGLIB proxies, false for JDK proxies. Default is false.
98
*/
99
boolean proxyTargetClass() default false;
100
101
/**
102
* Indicate how security advice should be applied.
103
* @return the advice mode. Default is PROXY.
104
*/
105
AdviceMode mode() default AdviceMode.PROXY;
106
107
/**
108
* Indicate the order in which the SecurityMethodInterceptor should be applied.
109
* @return the order value. Default is LOWEST_PRECEDENCE.
110
*/
111
int order() default Ordered.LOWEST_PRECEDENCE;
112
}
113
```
114
115
**Usage Example:**
116
117
```java
118
@Configuration
119
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true)
120
public class MethodSecurityConfig {
121
122
@Service
123
public class UserService {
124
125
@PreAuthorize("hasRole('ADMIN')")
126
public void deleteUser(Long userId) {
127
// Implementation
128
}
129
130
@PostAuthorize("returnObject.owner == authentication.name")
131
public User getUserById(Long id) {
132
// Implementation
133
}
134
}
135
}
136
```
137
138
### @EnableGlobalMethodSecurity (Deprecated)
139
140
Legacy method-level security configuration annotation.
141
142
```java { .api }
143
@Target(ElementType.TYPE)
144
@Retention(RetentionPolicy.RUNTIME)
145
@Documented
146
@Import(GlobalMethodSecurityConfiguration.class)
147
@Deprecated
148
public @interface EnableGlobalMethodSecurity {
149
boolean prePostEnabled() default false;
150
boolean securedEnabled() default false;
151
boolean jsr250Enabled() default false;
152
boolean proxyTargetClass() default false;
153
AdviceMode mode() default AdviceMode.PROXY;
154
int order() default Ordered.LOWEST_PRECEDENCE;
155
}
156
```
157
158
**Migration Note:** Use `@EnableMethodSecurity` instead for new applications.
159
160
### @EnableReactiveMethodSecurity
161
162
Reactive method security configuration for WebFlux applications.
163
164
```java { .api }
165
@Target(ElementType.TYPE)
166
@Retention(RetentionPolicy.RUNTIME)
167
@Documented
168
@Import(ReactiveMethodSecurityConfiguration.class)
169
public @interface EnableReactiveMethodSecurity {
170
/**
171
* Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
172
* to standard Java interface-based proxies.
173
* @return true to use CGLIB proxies, false for JDK proxies. Default is false.
174
*/
175
boolean proxyTargetClass() default false;
176
177
/**
178
* Indicate how security advice should be applied.
179
* @return the advice mode. Default is PROXY.
180
*/
181
AdviceMode mode() default AdviceMode.PROXY;
182
183
/**
184
* Indicate the order in which the SecurityMethodInterceptor should be applied.
185
* @return the order value. Default is LOWEST_PRECEDENCE.
186
*/
187
int order() default Ordered.LOWEST_PRECEDENCE;
188
189
/**
190
* Indicate whether to use AuthorizationManager for reactive method security.
191
* @return true to use AuthorizationManager, false for legacy approach. Default is true.
192
*/
193
boolean useAuthorizationManager() default true;
194
}
195
```
196
197
**Usage Example:**
198
199
```java
200
@Configuration
201
@EnableReactiveMethodSecurity
202
public class ReactiveSecurityConfig {
203
204
@Service
205
public class ReactiveUserService {
206
207
@PreAuthorize("hasRole('ADMIN')")
208
public Mono<Void> deleteUser(String userId) {
209
return userRepository.deleteById(userId);
210
}
211
212
@PostAuthorize("returnObject.owner == authentication.name")
213
public Mono<User> getUserById(String id) {
214
return userRepository.findById(id);
215
}
216
}
217
}
218
```
219
220
## Specialized Protocol Annotations
221
222
### @EnableRSocketSecurity
223
224
Enables RSocket security support for reactive messaging applications.
225
226
```java { .api }
227
@Target(ElementType.TYPE)
228
@Retention(RetentionPolicy.RUNTIME)
229
@Documented
230
@Import(RSocketSecurityConfiguration.class)
231
public @interface EnableRSocketSecurity {
232
}
233
```
234
235
**Usage Example:**
236
237
```java
238
@Configuration
239
@EnableRSocketSecurity
240
public class RSocketSecurityConfig {
241
242
@Bean
243
public PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
244
return rsocket
245
.authorizePayload(authorize -> authorize
246
.setup().hasRole("SETUP")
247
.route("user.*").hasRole("USER")
248
.anyRequest().authenticated()
249
)
250
.simpleAuthentication(Customizer.withDefaults())
251
.build();
252
}
253
}
254
```
255
256
## Common Patterns
257
258
### Combining Annotations
259
260
Multiple security annotations can be combined on the same configuration class:
261
262
```java
263
@Configuration
264
@EnableWebSecurity
265
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true)
266
public class ComprehensiveSecurityConfig {
267
268
@Bean
269
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
270
return http
271
.authorizeHttpRequests(authz -> authz
272
.requestMatchers("/admin/**").hasRole("ADMIN")
273
.anyRequest().authenticated()
274
)
275
.formLogin(Customizer.withDefaults())
276
.build();
277
}
278
}
279
```
280
281
### Custom Configuration Classes
282
283
Annotations can be applied to custom configuration classes that extend base configuration classes:
284
285
```java
286
@Configuration
287
@EnableWebSecurity
288
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
289
// Custom configuration methods
290
}
291
```
292
293
### Environment-Specific Configuration
294
295
Use Spring profiles to conditionally enable security features:
296
297
```java
298
@Configuration
299
@EnableWebSecurity
300
@Profile("!test")
301
public class ProductionSecurityConfig {
302
// Production security configuration
303
}
304
305
@Configuration
306
@EnableWebSecurity(debug = true)
307
@Profile("development")
308
public class DevelopmentSecurityConfig {
309
// Development security configuration with debug enabled
310
}
311
```