What it is
Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management. It simplifies securing applications by providing a flexible and intuitive API.
Shiro provides authentication, authorization, session management, and cryptography. It can secure applications through programmatic API, annotations, or configuration files, supporting both web and non-web environments.
Installation
Add dependency in pom.xml:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.11.0</version>
</dependency>Getting started
The smallest useful thing you can do with it, and what each part means.
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
UsernamePasswordToken token = new UsernamePasswordToken("user", "password");
Subject currentUser = SecurityUtils.getSubject();
currentUser.login(token);if(currentUser.hasRole("admin")) {
System.out.println("User has admin role");
}
if(currentUser.isPermitted("document:read")) {
System.out.println("User can read documents");
}Advanced usage
Where the library earns its place over a simpler alternative.
[users]
user = password, admin
[roles]
admin = document:read,document:writeimport org.apache.shiro.crypto.hash.Sha256Hash;
String hashedPassword = new Sha256Hash("password").toHex();Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
session.setAttribute("key", "value");@RequiresRoles("admin")
public void adminMethod() {
// only accessible by admin users
}Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- UnknownAccountException
- Occurs when a username does not exist. Verify the username or user store.
- IncorrectCredentialsException
- Occurs when the password does not match the stored credentials.
- AuthorizationException
- Occurs when a user attempts to access a resource they are not permitted to.
Best practices
- Always hash and salt passwords before storing them.
- Use Shiro’s permission system instead of hardcoding roles.
- Secure web applications using Shiro’s web filters.
- Combine annotations and programmatic checks for fine-grained security.
- Regularly update Shiro to patch security vulnerabilities.
Background
Why it exists, and what it was reacting to.
Apache Shiro was created to offer a simple yet comprehensive approach to application security in Java. It allows developers to secure web and enterprise applications without deep knowledge of complex security mechanisms. Shiro integrates seamlessly with any Java application and supports features such as password hashing, access control, and session management.
