A powerful and flexible open-source Java security framework providing authentication, authorization, session management, and cryptographic services
—
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.
The fundamental interface that all Realm implementations must implement.
/**
* A Realm is a security component that can access application-specific security entities.
*/
public interface Realm {
/**
* Returns the (application-unique) name assigned to this Realm.
* @return the (application-unique) name assigned to this Realm
*/
String getName();
/**
* Returns true if this Realm wishes to authenticate the Subject represented by the given AuthenticationToken instance.
* @param token the AuthenticationToken submitted for authentication
* @return true if this Realm can/will authenticate Subjects represented by specified token instances, false otherwise
*/
boolean supports(AuthenticationToken token);
/**
* Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given authentication token.
* @param token the authentication token containing the user's principal and credentials
* @return an AuthenticationInfo object containing account data resulting from the authentication ONLY if the lookup is successful
* @throws AuthenticationException if there is an error acquiring data or performing authentication logic for the specified token
*/
AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
}Foundation classes providing common realm functionality.
/**
* Simple implementation of the Realm interface that uses a set of configured user accounts and roles.
*/
public class SimpleAccountRealm implements Realm {
public SimpleAccountRealm();
/**
* Constructs a SimpleAccountRealm with the specified name.
* @param name the name assigned to this realm
*/
public SimpleAccountRealm(String name);
/**
* Adds an account to this realm.
* @param username the username
* @param password the password
*/
public void addAccount(String username, String password);
/**
* Adds an account with the specified roles to this realm.
* @param username the username
* @param password the password
* @param roles the account's assigned roles
*/
public void addAccount(String username, String password, String... roles);
/**
* Returns true if an account exists for the specified username.
* @param username the username to check
* @return true if an account exists for the specified username
*/
public boolean accountExists(String username);
public boolean supports(AuthenticationToken token);
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
}
/**
* A top-level abstract implementation of the Realm interface that only implements authentication support.
*/
public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {
/**
* Default constructor that initializes credential matching to simple equality checks.
*/
public AuthenticatingRealm();
/**
* Constructor specifying the CredentialsMatcher to use for credential verification.
* @param matcher the CredentialsMatcher to use for credential verification
*/
public AuthenticatingRealm(CredentialsMatcher matcher);
/**
* Sets the CredentialsMatcher used during authentication attempts.
* @param credentialsMatcher the CredentialsMatcher to use during authentication attempts
*/
public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher);
/**
* Returns the CredentialsMatcher used during authentication attempts.
* @return the CredentialsMatcher used during authentication attempts
*/
public CredentialsMatcher getCredentialsMatcher();
/**
* Sets the AuthenticationTokenClass supported by this realm.
* @param authenticationTokenClass the AuthenticationToken class supported by this realm
*/
public void setAuthenticationTokenClass(Class<? extends AuthenticationToken> authenticationTokenClass);
/**
* Returns the AuthenticationToken class supported by this realm.
* @return the AuthenticationToken class supported by this realm
*/
public Class getAuthenticationTokenClass();
/**
* Template method for subclasses to implement specific authentication logic.
* @param token the authentication token encapsulating the user's login credentials
* @return authentication information for the corresponding user account or null if no account
* @throws AuthenticationException if there is an error obtaining authentication information
*/
protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
public boolean supports(AuthenticationToken token);
public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
}
/**
* An AuthorizingRealm extends the AuthenticatingRealm's capabilities by adding Authorization (access control) support.
*/
public abstract class AuthorizingRealm extends AuthenticatingRealm implements Authorizer, Initializable, PermissionResolverAware, RolePermissionResolverAware {
/**
* Default constructor.
*/
public AuthorizingRealm();
/**
* Constructor specifying the CredentialsMatcher to use for credential verification.
* @param matcher the CredentialsMatcher to use for credential verification
*/
public AuthorizingRealm(CredentialsMatcher matcher);
/**
* Constructor specifying both the CredentialsMatcher and CacheManager to use.
* @param cacheManager the CacheManager to use for data caching
* @param matcher the CredentialsMatcher to use for credential verification
*/
public AuthorizingRealm(CacheManager cacheManager, CredentialsMatcher matcher);
/**
* Template method for subclasses to implement specific authorization logic.
* @param principals the principals of the Subject whose authorization information should be retrieved
* @return the authorization information for the specified subject's principals or null if no authorization information
*/
protected abstract AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
public boolean isPermitted(PrincipalCollection principals, String permission);
public boolean isPermitted(PrincipalCollection principals, Permission permission);
public boolean hasRole(PrincipalCollection principals, String roleIdentifier);
public void checkPermission(PrincipalCollection principals, String permission) throws AuthorizationException;
public void checkRole(PrincipalCollection principals, String roleIdentifier) throws AuthorizationException;
/**
* Clears the cached authorization information for the specified principals.
* @param principals the principals whose authorization information should be cleared from the cache
*/
protected void clearCachedAuthorizationInfo(PrincipalCollection principals);
/**
* Clears all authorization information from the cache.
*/
protected void clearAllCachedAuthorizationInfo();
}Realms that load security data from text-based configuration sources.
/**
* A text-based realm that loads user account data from text sources.
*/
public abstract class TextConfigurationRealm extends SimpleAccountRealm {
public TextConfigurationRealm();
/**
* Processes the specified text and extracts user account data.
* @param text the text to process
*/
protected void processDefinitions(String text);
/**
* Processes a single line of user account definition.
* @param line the line to process
*/
protected void processUserDefinition(String line);
/**
* Processes a single line of role definition.
* @param line the line to process
*/
protected void processRoleDefinition(String line);
}
/**
* A realm implementation that uses an INI configuration source for user account data.
*/
public class IniRealm extends TextConfigurationRealm {
public static final String USERS_SECTION_NAME = "users";
public static final String ROLES_SECTION_NAME = "roles";
public IniRealm();
/**
* Creates an IniRealm with the Ini instance that will be inspected for account data.
* @param ini the Ini instance containing account data
*/
public IniRealm(Ini ini);
/**
* Creates an IniRealm with the specified resource path to an INI source.
* @param resourcePath the resource path of the INI source
*/
public IniRealm(String resourcePath);
/**
* Sets the Ini instance used by this realm.
* @param ini the Ini instance containing user account data
*/
public void setIni(Ini ini);
/**
* Sets the resource path to an INI source.
* @param resourcePath the resource path to an INI source
*/
public void setResourcePath(String resourcePath);
}
/**
* A realm implementation that uses Java Properties files for user account data.
*/
public class PropertiesRealm extends TextConfigurationRealm {
public PropertiesRealm();
/**
* Sets the resource path to a Properties source.
* @param resourcePath the resource path to a Properties source
*/
public void setResourcePath(String resourcePath);
}Usage Examples:
// INI Realm configuration
IniRealm iniRealm = new IniRealm("classpath:users.ini");
// Or with direct Ini object
Ini ini = new Ini();
ini.setSectionProperty("users", "admin", "secret, admin");
ini.setSectionProperty("users", "user", "password, user");
ini.setSectionProperty("roles", "admin", "user:*");
ini.setSectionProperty("roles", "user", "user:read");
IniRealm realm = new IniRealm(ini);
// Properties Realm
PropertiesRealm propsRealm = new PropertiesRealm();
propsRealm.setResourcePath("classpath:users.properties");JDBC-based realm for database-backed authentication and authorization.
/**
* Realm that allows authentication and authorization via JDBC calls.
*/
public class JdbcRealm extends AuthorizingRealm {
/**
* Default query used to retrieve account data for authentication.
*/
protected static final String DEFAULT_AUTHENTICATION_QUERY = "select password from users where username = ?";
/**
* Default query used to retrieve roles for authorization.
*/
protected static final String DEFAULT_USER_ROLES_QUERY = "select role_name from user_roles where username = ?";
/**
* Default query used to retrieve permissions for authorization.
*/
protected static final String DEFAULT_PERMISSIONS_QUERY = "select permission from roles_permissions where role_name = ?";
public JdbcRealm();
/**
* Sets the DataSource that should be used to retrieve connections.
* @param dataSource the data source
*/
public void setDataSource(DataSource dataSource);
/**
* Returns the DataSource used by this realm.
* @return the DataSource used by this realm
*/
public DataSource getDataSource();
/**
* Sets the SQL query used to retrieve passwords during authentication.
* @param authenticationQuery the SQL query for authentication
*/
public void setAuthenticationQuery(String authenticationQuery);
/**
* Sets the SQL query used to retrieve role names during authorization.
* @param userRolesQuery the SQL query for user roles
*/
public void setUserRolesQuery(String userRolesQuery);
/**
* Sets the SQL query used to retrieve permissions during authorization.
* @param permissionsQuery the SQL query for permissions
*/
public void setPermissionsQuery(String permissionsQuery);
/**
* Sets the query used to retrieve salt for the corresponding user.
* @param saltQuery the salt query
*/
public void setSaltQuery(String saltQuery);
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
}Usage Example:
// Configure JDBC realm
JdbcRealm jdbcRealm = new JdbcRealm();
jdbcRealm.setDataSource(dataSource);
// Custom queries (optional)
jdbcRealm.setAuthenticationQuery("SELECT password FROM users WHERE username = ?");
jdbcRealm.setUserRolesQuery("SELECT role FROM user_roles WHERE username = ?");
jdbcRealm.setPermissionsQuery("SELECT permission FROM role_permissions WHERE role = ?");
DefaultSecurityManager securityManager = new DefaultSecurityManager(jdbcRealm);Realms for integration with LDAP and Active Directory systems.
/**
* Base class for LDAP-based realms.
*/
public abstract class AbstractLdapRealm extends AuthorizingRealm {
public AbstractLdapRealm();
/**
* Sets the LdapContextFactory used to acquire connections to the LDAP directory.
* @param ldapContextFactory the LdapContextFactory used to acquire LDAP connections
*/
public void setLdapContextFactory(LdapContextFactory ldapContextFactory);
/**
* Returns the LdapContextFactory used to acquire LDAP connections.
* @return the LdapContextFactory used to acquire LDAP connections
*/
public LdapContextFactory getLdapContextFactory();
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;
protected abstract AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
}
/**
* LDAP realm implementation using JNDI.
*/
public class JndiLdapRealm extends AbstractLdapRealm {
public static final String DEFAULT_USER_DN_TEMPLATE = "uid={0},ou=users,dc=mycompany,dc=com";
public JndiLdapRealm();
/**
* Sets the template used to construct the user DN from the username.
* @param template the user DN template
*/
public void setUserDnTemplate(String template);
/**
* Returns the template used to construct user DNs.
* @return the user DN template
*/
public String getUserDnTemplate();
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
}
/**
* Default LDAP realm implementation.
*/
public class DefaultLdapRealm extends AbstractLdapRealm {
public DefaultLdapRealm();
/**
* Sets the LDAP search base for users.
* @param userSearchBase the user search base
*/
public void setUserSearchBase(String userSearchBase);
/**
* Sets the LDAP search filter for finding users.
* @param userSearchFilter the user search filter
*/
public void setUserSearchFilter(String userSearchFilter);
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
}
/**
* Realm implementation for Microsoft Active Directory.
*/
public class ActiveDirectoryRealm extends AbstractLdapRealm {
private static final String DEFAULT_PRINCIPAL_SUFFIX = "";
public ActiveDirectoryRealm();
/**
* Sets the principal suffix that will be appended to usernames for authentication.
* @param principalSuffix the principal suffix (e.g., "@company.com")
*/
public void setPrincipalSuffix(String principalSuffix);
/**
* Sets the search base for finding Active Directory users.
* @param searchBase the search base
*/
public void setSearchBase(String searchBase);
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals);
}Usage Examples:
// JNDI LDAP Realm
JndiLdapRealm ldapRealm = new JndiLdapRealm();
ldapRealm.setUserDnTemplate("uid={0},ou=users,dc=company,dc=com");
JndiLdapContextFactory contextFactory = new JndiLdapContextFactory();
contextFactory.setUrl("ldap://ldap.company.com:389");
ldapRealm.setLdapContextFactory(contextFactory);
// Active Directory Realm
ActiveDirectoryRealm adRealm = new ActiveDirectoryRealm();
adRealm.setPrincipalSuffix("@company.com");
adRealm.setSearchBase("CN=Users,DC=company,DC=com");
JndiLdapContextFactory adContextFactory = new JndiLdapContextFactory();
adContextFactory.setUrl("ldap://ad.company.com:389");
adRealm.setLdapContextFactory(adContextFactory);Factory for creating LDAP connections.
/**
* Interface for creating LDAP contexts.
*/
public interface LdapContextFactory {
/**
* Creates an LDAP context with system credentials.
* @return the LDAP context
* @throws NamingException if context creation fails
*/
LdapContext getSystemLdapContext() throws NamingException;
/**
* Creates an LDAP context with the specified principal and credentials.
* @param principal the principal for authentication
* @param credentials the credentials for authentication
* @return the LDAP context
* @throws NamingException if context creation fails
*/
LdapContext getLdapContext(String principal, String credentials) throws NamingException;
}
/**
* JNDI implementation of LdapContextFactory.
*/
public class JndiLdapContextFactory implements LdapContextFactory {
public JndiLdapContextFactory();
/**
* Sets the LDAP URL.
* @param url the LDAP URL
*/
public void setUrl(String url);
/**
* Sets the system username for LDAP connections.
* @param systemUsername the system username
*/
public void setSystemUsername(String systemUsername);
/**
* Sets the system password for LDAP connections.
* @param systemPassword the system password
*/
public void setSystemPassword(String systemPassword);
/**
* Sets additional environment properties for LDAP connections.
* @param environment the environment properties
*/
public void setEnvironment(Map<String, String> environment);
public LdapContext getSystemLdapContext() throws NamingException;
public LdapContext getLdapContext(String principal, String credentials) throws NamingException;
}Base class providing caching capabilities for realms.
/**
* A CachingRealm is a Realm that provides caching support for its authentication and authorization data.
*/
public abstract class CachingRealm implements Realm, Nameable, CacheManagerAware, LogoutAware {
public CachingRealm();
/**
* Sets the CacheManager to be used for data caching.
* @param cacheManager the CacheManager to use for data caching
*/
public void setCacheManager(CacheManager cacheManager);
/**
* Returns the CacheManager used for data caching.
* @return the CacheManager used for data caching
*/
public CacheManager getCacheManager();
/**
* Sets whether or not caching should be used if a CacheManager has been configured.
* @param cachingEnabled whether or not to enable caching
*/
public void setCachingEnabled(boolean cachingEnabled);
/**
* Returns true if caching is enabled, false otherwise.
* @return true if caching is enabled, false otherwise
*/
public boolean isCachingEnabled();
/**
* Sets the name of the cache used for authentication data.
* @param authenticationCacheName the authentication cache name
*/
public void setAuthenticationCacheName(String authenticationCacheName);
/**
* Clears any cached data.
*/
protected void clearCache();
public void onLogout(PrincipalCollection principals);
}Usage Example:
// Enable caching for a custom realm
public class MyCustomRealm extends AuthorizingRealm {
public MyCustomRealm() {
// Enable authentication and authorization caching
setAuthenticationCachingEnabled(true);
setAuthorizationCachingEnabled(true);
// Set custom cache names
setAuthenticationCacheName("authenticationCache");
setAuthorizationCacheName("authorizationCache");
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// Implementation will be automatically cached
return createAuthenticationInfo(token);
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// Implementation will be automatically cached
return createAuthorizationInfo(principals);
}
}public interface Nameable {
void setName(String name);
String getName();
}
public interface CacheManagerAware {
void setCacheManager(CacheManager cacheManager);
}
public interface Initializable {
void init() throws ShiroException;
}
public interface Destroyable {
void destroy() throws Exception;
}Install with Tessl CLI
npx tessl i tessl/maven-org-apache-shiro--shiro-core