0
# Realms
1
2
Realms are Apache Shiro's data source abstractions that connect the framework to your security data sources like databases, LDAP directories, or configuration files. They handle both authentication and authorization data retrieval and serve as the bridge between Shiro and your application's security data.
3
4
## Capabilities
5
6
### Core Realm Interface
7
8
The fundamental interface that all Realm implementations must implement.
9
10
```java { .api }
11
/**
12
* A Realm is a security component that can access application-specific security entities.
13
*/
14
public interface Realm {
15
/**
16
* Returns the (application-unique) name assigned to this Realm.
17
* @return the (application-unique) name assigned to this Realm
18
*/
19
String getName();
20
21
/**
22
* Returns true if this Realm wishes to authenticate the Subject represented by the given AuthenticationToken instance.
23
* @param token the AuthenticationToken submitted for authentication
24
* @return true if this Realm can/will authenticate Subjects represented by specified token instances, false otherwise
25
*/
26
boolean supports(AuthenticationToken token);
27
28
/**
29
* Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given authentication token.
30
* @param token the authentication token containing the user's principal and credentials
31
* @return an AuthenticationInfo object containing account data resulting from the authentication ONLY if the lookup is successful
32
* @throws AuthenticationException if there is an error acquiring data or performing authentication logic for the specified token
33
*/
34
AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
35
}
36
```
37
38
### Base Realm Implementations
39
40
Foundation classes providing common realm functionality.
41
42
```java { .api }
43
/**
44
* Simple implementation of the Realm interface that uses a set of configured user accounts and roles.
45
*/
46
public class SimpleAccountRealm implements Realm {
47
public SimpleAccountRealm();
48
49
/**
50
* Constructs a SimpleAccountRealm with the specified name.
51
* @param name the name assigned to this realm
52
*/
53
public SimpleAccountRealm(String name);
54
55
/**
56
* Adds an account to this realm.
57
* @param username the username
58
* @param password the password
59
*/
60
public void addAccount(String username, String password);
61
62
/**
63
* Adds an account with the specified roles to this realm.
64
* @param username the username
65
* @param password the password
66
* @param roles the account's assigned roles
67
*/
68
public void addAccount(String username, String password, String... roles);
69
70
/**
71
* Returns true if an account exists for the specified username.
72
* @param username the username to check
73
* @return true if an account exists for the specified username
74
*/
75
public boolean accountExists(String username);
76
77
public boolean supports(AuthenticationToken token);
78
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
79
}
80
81
/**
82
* A top-level abstract implementation of the Realm interface that only implements authentication support.
83
*/
84
public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {
85
/**
86
* Default constructor that initializes credential matching to simple equality checks.
87
*/
88
public AuthenticatingRealm();
89
90
/**
91
* Constructor specifying the CredentialsMatcher to use for credential verification.
92
* @param matcher the CredentialsMatcher to use for credential verification
93
*/
94
public AuthenticatingRealm(CredentialsMatcher matcher);
95
96
/**
97
* Sets the CredentialsMatcher used during authentication attempts.
98
* @param credentialsMatcher the CredentialsMatcher to use during authentication attempts
99
*/
100
public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher);
101
102
/**
103
* Returns the CredentialsMatcher used during authentication attempts.
104
* @return the CredentialsMatcher used during authentication attempts
105
*/
106
public CredentialsMatcher getCredentialsMatcher();
107
108
/**
109
* Sets the AuthenticationTokenClass supported by this realm.
110
* @param authenticationTokenClass the AuthenticationToken class supported by this realm
111
*/
112
public void setAuthenticationTokenClass(Class<? extends AuthenticationToken> authenticationTokenClass);
113
114
/**
115
* Returns the AuthenticationToken class supported by this realm.
116
* @return the AuthenticationToken class supported by this realm
117
*/
118
public Class getAuthenticationTokenClass();
119
120
/**
121
* Template method for subclasses to implement specific authentication logic.
122
* @param token the authentication token encapsulating the user's login credentials
123
* @return authentication information for the corresponding user account or null if no account
124
* @throws AuthenticationException if there is an error obtaining authentication information
125
*/
126
protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
127
128
public boolean supports(AuthenticationToken token);
129
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
130
}
131
132
/**
133
* An AuthorizingRealm extends the AuthenticatingRealm's capabilities by adding Authorization (access control) support.
134
*/
135
public abstract class AuthorizingRealm extends AuthenticatingRealm implements Authorizer, Initializable, PermissionResolverAware, RolePermissionResolverAware {
136
/**
137
* Default constructor.
138
*/
139
public AuthorizingRealm();
140
141
/**
142
* Constructor specifying the CredentialsMatcher to use for credential verification.
143
* @param matcher the CredentialsMatcher to use for credential verification
144
*/
145
public AuthorizingRealm(CredentialsMatcher matcher);
146
147
/**
148
* Constructor specifying both the CredentialsMatcher and CacheManager to use.
149
* @param cacheManager the CacheManager to use for data caching
150
* @param matcher the CredentialsMatcher to use for credential verification
151
*/
152
public AuthorizingRealm(CacheManager cacheManager, CredentialsMatcher matcher);
153
154
/**
155
* Template method for subclasses to implement specific authorization logic.
156
* @param principals the principals of the Subject whose authorization information should be retrieved
157
* @return the authorization information for the specified subject's principals or null if no authorization information
158
*/
159
protected abstract AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
160
161
public boolean isPermitted(PrincipalCollection principals, String permission);
162
public boolean isPermitted(PrincipalCollection principals, Permission permission);
163
public boolean hasRole(PrincipalCollection principals, String roleIdentifier);
164
public void checkPermission(PrincipalCollection principals, String permission) throws AuthorizationException;
165
public void checkRole(PrincipalCollection principals, String roleIdentifier) throws AuthorizationException;
166
167
/**
168
* Clears the cached authorization information for the specified principals.
169
* @param principals the principals whose authorization information should be cleared from the cache
170
*/
171
protected void clearCachedAuthorizationInfo(PrincipalCollection principals);
172
173
/**
174
* Clears all authorization information from the cache.
175
*/
176
protected void clearAllCachedAuthorizationInfo();
177
}
178
```
179
180
### Text-Based Realms
181
182
Realms that load security data from text-based configuration sources.
183
184
```java { .api }
185
/**
186
* A text-based realm that loads user account data from text sources.
187
*/
188
public abstract class TextConfigurationRealm extends SimpleAccountRealm {
189
public TextConfigurationRealm();
190
191
/**
192
* Processes the specified text and extracts user account data.
193
* @param text the text to process
194
*/
195
protected void processDefinitions(String text);
196
197
/**
198
* Processes a single line of user account definition.
199
* @param line the line to process
200
*/
201
protected void processUserDefinition(String line);
202
203
/**
204
* Processes a single line of role definition.
205
* @param line the line to process
206
*/
207
protected void processRoleDefinition(String line);
208
}
209
210
/**
211
* A realm implementation that uses an INI configuration source for user account data.
212
*/
213
public class IniRealm extends TextConfigurationRealm {
214
public static final String USERS_SECTION_NAME = "users";
215
public static final String ROLES_SECTION_NAME = "roles";
216
217
public IniRealm();
218
219
/**
220
* Creates an IniRealm with the Ini instance that will be inspected for account data.
221
* @param ini the Ini instance containing account data
222
*/
223
public IniRealm(Ini ini);
224
225
/**
226
* Creates an IniRealm with the specified resource path to an INI source.
227
* @param resourcePath the resource path of the INI source
228
*/
229
public IniRealm(String resourcePath);
230
231
/**
232
* Sets the Ini instance used by this realm.
233
* @param ini the Ini instance containing user account data
234
*/
235
public void setIni(Ini ini);
236
237
/**
238
* Sets the resource path to an INI source.
239
* @param resourcePath the resource path to an INI source
240
*/
241
public void setResourcePath(String resourcePath);
242
}
243
244
/**
245
* A realm implementation that uses Java Properties files for user account data.
246
*/
247
public class PropertiesRealm extends TextConfigurationRealm {
248
public PropertiesRealm();
249
250
/**
251
* Sets the resource path to a Properties source.
252
* @param resourcePath the resource path to a Properties source
253
*/
254
public void setResourcePath(String resourcePath);
255
}
256
```
257
258
**Usage Examples:**
259
260
```java
261
// INI Realm configuration
262
IniRealm iniRealm = new IniRealm("classpath:users.ini");
263
264
// Or with direct Ini object
265
Ini ini = new Ini();
266
ini.setSectionProperty("users", "admin", "secret, admin");
267
ini.setSectionProperty("users", "user", "password, user");
268
ini.setSectionProperty("roles", "admin", "user:*");
269
ini.setSectionProperty("roles", "user", "user:read");
270
IniRealm realm = new IniRealm(ini);
271
272
// Properties Realm
273
PropertiesRealm propsRealm = new PropertiesRealm();
274
propsRealm.setResourcePath("classpath:users.properties");
275
```
276
277
### Database Realm
278
279
JDBC-based realm for database-backed authentication and authorization.
280
281
```java { .api }
282
/**
283
* Realm that allows authentication and authorization via JDBC calls.
284
*/
285
public class JdbcRealm extends AuthorizingRealm {
286
/**
287
* Default query used to retrieve account data for authentication.
288
*/
289
protected static final String DEFAULT_AUTHENTICATION_QUERY = "select password from users where username = ?";
290
291
/**
292
* Default query used to retrieve roles for authorization.
293
*/
294
protected static final String DEFAULT_USER_ROLES_QUERY = "select role_name from user_roles where username = ?";
295
296
/**
297
* Default query used to retrieve permissions for authorization.
298
*/
299
protected static final String DEFAULT_PERMISSIONS_QUERY = "select permission from roles_permissions where role_name = ?";
300
301
public JdbcRealm();
302
303
/**
304
* Sets the DataSource that should be used to retrieve connections.
305
* @param dataSource the data source
306
*/
307
public void setDataSource(DataSource dataSource);
308
309
/**
310
* Returns the DataSource used by this realm.
311
* @return the DataSource used by this realm
312
*/
313
public DataSource getDataSource();
314
315
/**
316
* Sets the SQL query used to retrieve passwords during authentication.
317
* @param authenticationQuery the SQL query for authentication
318
*/
319
public void setAuthenticationQuery(String authenticationQuery);
320
321
/**
322
* Sets the SQL query used to retrieve role names during authorization.
323
* @param userRolesQuery the SQL query for user roles
324
*/
325
public void setUserRolesQuery(String userRolesQuery);
326
327
/**
328
* Sets the SQL query used to retrieve permissions during authorization.
329
* @param permissionsQuery the SQL query for permissions
330
*/
331
public void setPermissionsQuery(String permissionsQuery);
332
333
/**
334
* Sets the query used to retrieve salt for the corresponding user.
335
* @param saltQuery the salt query
336
*/
337
public void setSaltQuery(String saltQuery);
338
339
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
340
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
341
}
342
```
343
344
**Usage Example:**
345
346
```java
347
// Configure JDBC realm
348
JdbcRealm jdbcRealm = new JdbcRealm();
349
jdbcRealm.setDataSource(dataSource);
350
351
// Custom queries (optional)
352
jdbcRealm.setAuthenticationQuery("SELECT password FROM users WHERE username = ?");
353
jdbcRealm.setUserRolesQuery("SELECT role FROM user_roles WHERE username = ?");
354
jdbcRealm.setPermissionsQuery("SELECT permission FROM role_permissions WHERE role = ?");
355
356
DefaultSecurityManager securityManager = new DefaultSecurityManager(jdbcRealm);
357
```
358
359
### LDAP Realms
360
361
Realms for integration with LDAP and Active Directory systems.
362
363
```java { .api }
364
/**
365
* Base class for LDAP-based realms.
366
*/
367
public abstract class AbstractLdapRealm extends AuthorizingRealm {
368
public AbstractLdapRealm();
369
370
/**
371
* Sets the LdapContextFactory used to acquire connections to the LDAP directory.
372
* @param ldapContextFactory the LdapContextFactory used to acquire LDAP connections
373
*/
374
public void setLdapContextFactory(LdapContextFactory ldapContextFactory);
375
376
/**
377
* Returns the LdapContextFactory used to acquire LDAP connections.
378
* @return the LdapContextFactory used to acquire LDAP connections
379
*/
380
public LdapContextFactory getLdapContextFactory();
381
382
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
383
protected abstract AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
384
}
385
386
/**
387
* LDAP realm implementation using JNDI.
388
*/
389
public class JndiLdapRealm extends AbstractLdapRealm {
390
public static final String DEFAULT_USER_DN_TEMPLATE = "uid={0},ou=users,dc=mycompany,dc=com";
391
392
public JndiLdapRealm();
393
394
/**
395
* Sets the template used to construct the user DN from the username.
396
* @param template the user DN template
397
*/
398
public void setUserDnTemplate(String template);
399
400
/**
401
* Returns the template used to construct user DNs.
402
* @return the user DN template
403
*/
404
public String getUserDnTemplate();
405
406
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
407
}
408
409
/**
410
* Default LDAP realm implementation.
411
*/
412
public class DefaultLdapRealm extends AbstractLdapRealm {
413
public DefaultLdapRealm();
414
415
/**
416
* Sets the LDAP search base for users.
417
* @param userSearchBase the user search base
418
*/
419
public void setUserSearchBase(String userSearchBase);
420
421
/**
422
* Sets the LDAP search filter for finding users.
423
* @param userSearchFilter the user search filter
424
*/
425
public void setUserSearchFilter(String userSearchFilter);
426
427
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
428
}
429
430
/**
431
* Realm implementation for Microsoft Active Directory.
432
*/
433
public class ActiveDirectoryRealm extends AbstractLdapRealm {
434
private static final String DEFAULT_PRINCIPAL_SUFFIX = "";
435
436
public ActiveDirectoryRealm();
437
438
/**
439
* Sets the principal suffix that will be appended to usernames for authentication.
440
* @param principalSuffix the principal suffix (e.g., "@company.com")
441
*/
442
public void setPrincipalSuffix(String principalSuffix);
443
444
/**
445
* Sets the search base for finding Active Directory users.
446
* @param searchBase the search base
447
*/
448
public void setSearchBase(String searchBase);
449
450
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
451
}
452
```
453
454
**Usage Examples:**
455
456
```java
457
// JNDI LDAP Realm
458
JndiLdapRealm ldapRealm = new JndiLdapRealm();
459
ldapRealm.setUserDnTemplate("uid={0},ou=users,dc=company,dc=com");
460
461
JndiLdapContextFactory contextFactory = new JndiLdapContextFactory();
462
contextFactory.setUrl("ldap://ldap.company.com:389");
463
ldapRealm.setLdapContextFactory(contextFactory);
464
465
// Active Directory Realm
466
ActiveDirectoryRealm adRealm = new ActiveDirectoryRealm();
467
adRealm.setPrincipalSuffix("@company.com");
468
adRealm.setSearchBase("CN=Users,DC=company,DC=com");
469
470
JndiLdapContextFactory adContextFactory = new JndiLdapContextFactory();
471
adContextFactory.setUrl("ldap://ad.company.com:389");
472
adRealm.setLdapContextFactory(adContextFactory);
473
```
474
475
### LDAP Context Factory
476
477
Factory for creating LDAP connections.
478
479
```java { .api }
480
/**
481
* Interface for creating LDAP contexts.
482
*/
483
public interface LdapContextFactory {
484
/**
485
* Creates an LDAP context with system credentials.
486
* @return the LDAP context
487
* @throws NamingException if context creation fails
488
*/
489
LdapContext getSystemLdapContext() throws NamingException;
490
491
/**
492
* Creates an LDAP context with the specified principal and credentials.
493
* @param principal the principal for authentication
494
* @param credentials the credentials for authentication
495
* @return the LDAP context
496
* @throws NamingException if context creation fails
497
*/
498
LdapContext getLdapContext(String principal, String credentials) throws NamingException;
499
}
500
501
/**
502
* JNDI implementation of LdapContextFactory.
503
*/
504
public class JndiLdapContextFactory implements LdapContextFactory {
505
public JndiLdapContextFactory();
506
507
/**
508
* Sets the LDAP URL.
509
* @param url the LDAP URL
510
*/
511
public void setUrl(String url);
512
513
/**
514
* Sets the system username for LDAP connections.
515
* @param systemUsername the system username
516
*/
517
public void setSystemUsername(String systemUsername);
518
519
/**
520
* Sets the system password for LDAP connections.
521
* @param systemPassword the system password
522
*/
523
public void setSystemPassword(String systemPassword);
524
525
/**
526
* Sets additional environment properties for LDAP connections.
527
* @param environment the environment properties
528
*/
529
public void setEnvironment(Map<String, String> environment);
530
531
public LdapContext getSystemLdapContext() throws NamingException;
532
public LdapContext getLdapContext(String principal, String credentials) throws NamingException;
533
}
534
```
535
536
### Caching Realm Support
537
538
Base class providing caching capabilities for realms.
539
540
```java { .api }
541
/**
542
* A CachingRealm is a Realm that provides caching support for its authentication and authorization data.
543
*/
544
public abstract class CachingRealm implements Realm, Nameable, CacheManagerAware, LogoutAware {
545
public CachingRealm();
546
547
/**
548
* Sets the CacheManager to be used for data caching.
549
* @param cacheManager the CacheManager to use for data caching
550
*/
551
public void setCacheManager(CacheManager cacheManager);
552
553
/**
554
* Returns the CacheManager used for data caching.
555
* @return the CacheManager used for data caching
556
*/
557
public CacheManager getCacheManager();
558
559
/**
560
* Sets whether or not caching should be used if a CacheManager has been configured.
561
* @param cachingEnabled whether or not to enable caching
562
*/
563
public void setCachingEnabled(boolean cachingEnabled);
564
565
/**
566
* Returns true if caching is enabled, false otherwise.
567
* @return true if caching is enabled, false otherwise
568
*/
569
public boolean isCachingEnabled();
570
571
/**
572
* Sets the name of the cache used for authentication data.
573
* @param authenticationCacheName the authentication cache name
574
*/
575
public void setAuthenticationCacheName(String authenticationCacheName);
576
577
/**
578
* Clears any cached data.
579
*/
580
protected void clearCache();
581
582
public void onLogout(PrincipalCollection principals);
583
}
584
```
585
586
**Usage Example:**
587
588
```java
589
// Enable caching for a custom realm
590
public class MyCustomRealm extends AuthorizingRealm {
591
592
public MyCustomRealm() {
593
// Enable authentication and authorization caching
594
setAuthenticationCachingEnabled(true);
595
setAuthorizationCachingEnabled(true);
596
597
// Set custom cache names
598
setAuthenticationCacheName("authenticationCache");
599
setAuthorizationCacheName("authorizationCache");
600
}
601
602
@Override
603
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
604
// Implementation will be automatically cached
605
return createAuthenticationInfo(token);
606
}
607
608
@Override
609
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
610
// Implementation will be automatically cached
611
return createAuthorizationInfo(principals);
612
}
613
}
614
```
615
616
## Types
617
618
```java { .api }
619
public interface Nameable {
620
void setName(String name);
621
String getName();
622
}
623
624
public interface CacheManagerAware {
625
void setCacheManager(CacheManager cacheManager);
626
}
627
628
public interface Initializable {
629
void init() throws ShiroException;
630
}
631
632
public interface Destroyable {
633
void destroy() throws Exception;
634
}
635
```