Language: Java
Security
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.
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.
Add dependency in pom.xml:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.11.0</version>
</dependency>Add dependency in build.gradle:
testImplementation 'org.apache.shiro:shiro-core:1.11.0'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.
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);Authenticates a user using a username and password token.
if(currentUser.hasRole("admin")) {
System.out.println("User has admin role");
}
if(currentUser.isPermitted("document:read")) {
System.out.println("User can read documents");
}Checks if the current user has a specific role or permission.
[users]
user = password, admin
[roles]
admin = document:read,document:writeDefines users and roles with permissions in an INI configuration file.
import org.apache.shiro.crypto.hash.Sha256Hash;
String hashedPassword = new Sha256Hash("password").toHex();Hashes a password using SHA-256 for secure storage.
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
session.setAttribute("key", "value");Stores and retrieves data in a Shiro-managed session.
@RequiresRoles("admin")
public void adminMethod() {
// only accessible by admin users
}Secures methods using annotations for role-based access control.
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.