A powerful and flexible open-source Java security framework providing authentication, authorization, session management, and cryptographic services
—
The Subject interface represents the security-specific view of the current user and serves as the primary interface for all security operations in Apache Shiro. It provides methods for authentication, authorization, session management, and secure execution of code blocks.
Methods for logging in, checking authentication status, and logging out users.
/**
* Performs a login attempt for this Subject/user with the given authentication token.
* @param token the authentication token encapsulating the user's login credentials
* @throws AuthenticationException if the authentication attempt fails
*/
void login(AuthenticationToken token) throws AuthenticationException;
/**
* Returns true if this Subject has successfully completed authentication.
* @return true if authenticated, false otherwise
*/
boolean isAuthenticated();
/**
* Returns true if this Subject is remembered from a successful authentication during a previous session.
* @return true if remembered, false otherwise
*/
boolean isRemembered();
/**
* Logs out this Subject and invalidates and/or removes any associated entities.
*/
void logout();Usage Example:
Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("username", "password");
token.setRememberMe(true);
try {
currentUser.login(token);
System.out.println("Login successful");
} catch (UnknownAccountException uae) {
System.out.println("Unknown account");
} catch (IncorrectCredentialsException ice) {
System.out.println("Incorrect credentials");
} catch (LockedAccountException lae) {
System.out.println("Account locked");
} catch (AuthenticationException ae) {
System.out.println("Authentication failed");
}Methods for checking roles and permissions, with both boolean return and exception-throwing variants.
/**
* Returns true if this Subject has the specified role, false otherwise.
* @param roleIdentifier the application-specific role identifier (usually a role id or role name)
* @return true if this Subject has the specified role, false otherwise
*/
boolean hasRole(String roleIdentifier);
/**
* Checks if this Subject implies the given roles and returns a boolean array.
* @param roleIdentifiers the application-specific role identifiers to check
* @return a boolean array where indices correspond to the index of the roles in the given identifiers
*/
boolean[] hasRoles(List<String> roleIdentifiers);
/**
* Returns true if this Subject has all the specified roles, false otherwise.
* @param roleIdentifiers the application-specific role identifiers to check
* @return true if this Subject has all the specified roles, false otherwise
*/
boolean hasAllRoles(Collection<String> roleIdentifiers);
/**
* Asserts this Subject has the specified role by returning quietly if they do or throwing an AuthorizationException if they do not.
* @param roleIdentifier the application-specific role identifier
* @throws AuthorizationException if this Subject does not have the role
*/
void checkRole(String roleIdentifier) throws AuthorizationException;
/**
* Same as checkRole(String) but for multiple roles.
* @param roleIdentifiers the application-specific role identifiers to check
* @throws AuthorizationException if this Subject does not have all specified roles
*/
void checkRoles(Collection<String> roleIdentifiers) throws AuthorizationException;Permission checking methods:
/**
* Returns true if this Subject is permitted to perform an action or access a resource summarized by the specified permission string.
* @param permission a permission string
* @return true if permitted, false otherwise
*/
boolean isPermitted(String permission);
/**
* Returns true if this Subject is permitted to perform an action or access a resource summarized by the specified permission.
* @param permission a permission object
* @return true if permitted, false otherwise
*/
boolean isPermitted(Permission permission);
/**
* Checks if this Subject implies the given permissions and returns a boolean array.
* @param permissions the permissions to check
* @return a boolean array where indices correspond to the index of the permissions in the given list
*/
boolean[] isPermitted(String... permissions);
/**
* Returns true if this Subject is permitted all of the specified permissions, false otherwise.
* @param permissions the permissions to check
* @return true if permitted all, false otherwise
*/
boolean isPermittedAll(String... permissions);
/**
* Ensures this Subject implies the specified permission.
* @param permission a permission string
* @throws AuthorizationException if this Subject does not have the permission
*/
void checkPermission(String permission) throws AuthorizationException;
/**
* Ensures this Subject implies the specified permission.
* @param permission a permission object
* @throws AuthorizationException if this Subject does not have the permission
*/
void checkPermission(Permission permission) throws AuthorizationException;
/**
* Ensures this Subject implies all of the specified permissions.
* @param permissions the permissions to check
* @throws AuthorizationException if this Subject does not have all permissions
*/
void checkPermissions(String... permissions) throws AuthorizationException;Usage Example:
Subject currentUser = SecurityUtils.getSubject();
// Role checking
if (currentUser.hasRole("admin")) {
System.out.println("User is an admin");
} else if (currentUser.hasRole("user")) {
System.out.println("User is a regular user");
}
// Permission checking
if (currentUser.isPermitted("user:create")) {
System.out.println("User can create other users");
}
if (currentUser.isPermitted("document:read:123")) {
System.out.println("User can read document 123");
}
// Exception-throwing authorization
try {
currentUser.checkPermission("admin:delete");
// User has permission, continue with operation
performAdminDeletion();
} catch (AuthorizationException e) {
System.out.println("User not authorized for admin deletion");
}Methods for working with the Subject's session.
/**
* Returns the application Session associated with this Subject.
* @return the application Session associated with this Subject
*/
Session getSession();
/**
* Returns the application Session associated with this Subject.
* @param create boolean argument determining if a session should be created if one does not exist
* @return the application Session associated with this Subject or null if create is false and no session exists
*/
Session getSession(boolean create);Usage Example:
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
// Store data in session
session.setAttribute("userPreferences", userPrefs);
// Retrieve data from session
Object preferences = session.getAttribute("userPreferences");
// Session management
session.touch(); // Update last access time
session.setTimeout(30 * 60 * 1000); // 30 minutes timeoutMethods for accessing the Subject's identity information.
/**
* Returns this Subject's application-wide uniquely identifying principal, or null if this Subject is anonymous.
* @return this Subject's application-wide uniquely identifying principal, or null if this Subject is anonymous
*/
Object getPrincipal();
/**
* Returns this Subject's principals (identifying attributes) in the form of a PrincipalCollection.
* @return this Subject's identifying attributes, or an empty PrincipalCollection if this Subject is anonymous
*/
PrincipalCollection getPrincipals();Methods for executing code blocks with the Subject's security context automatically applied.
/**
* Executes a Callable with this Subject instance as the calling thread's Subject.
* @param callable the callable to execute as this Subject
* @return the result returned by the callable
* @throws ExecutionException if the callable throws an exception
*/
<V> V execute(Callable<V> callable) throws ExecutionException;
/**
* Executes a Runnable with this Subject instance as the calling thread's Subject.
* @param runnable the runnable to execute as this Subject
*/
void execute(Runnable runnable);
/**
* Associates the specified Callable with this Subject instance and then executes it on the currently running thread.
* @param callable the callable to associate with this subject and then execute
* @return the result of the callable execution
* @throws ExecutionException if the callable execution throws an exception
*/
<V> V associateWith(Callable<V> callable) throws ExecutionException;
/**
* Associates the specified Runnable with this Subject instance and then executes it on the currently running thread.
* @param runnable the runnable to associate with this subject and then execute
*/
void associateWith(Runnable runnable);Usage Example:
Subject adminUser = SecurityUtils.getSubject();
// Execute code block with admin context
String result = adminUser.execute(new Callable<String>() {
public String call() throws Exception {
// This code runs with adminUser's security context
performSecureOperation();
return "Operation completed";
}
});
// Using lambda (Java 8+)
String result2 = adminUser.execute(() -> {
return performAnotherSecureOperation();
});public interface PrincipalCollection extends Iterable, Serializable {
Object getPrimaryPrincipal();
<T> T oneByType(Class<T> type);
<T> Collection<T> byType(Class<T> type);
List asList();
Set asSet();
boolean isEmpty();
}
public class ExecutionException extends Exception {
public ExecutionException(Throwable cause);
public ExecutionException(String message, Throwable cause);
}Install with Tessl CLI
npx tessl i tessl/maven-org-apache-shiro--shiro-core